Problem 1: BY using defaulthighlighter, I can make the focused lines change to blue. Now I want to change it to other colors. Do anyone know how to change this param
To set the selection background color, use setSelectionColor (illustrated below but not used).
I don't really understand what you're saying with it always appears at the bottom of the window. I want to have it at the top but I am guessing (and I may be wrong here) that your textarea is in a scrollpane and that by highlighting the text it scrolls to the end of your selection, so I suggest to set the caret position after highlighting the text.
Here is a sample of what I understood. Let me know if this is not what you're looking for:
import java.awt.Color;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
public class Test {
public static void main(final String[] args) throws MalformedURLException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
init();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private static void init() throws BadLocationException {
JFrame frame = new JFrame();
final JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
textArea.setText("Something. Something else.\nA second line\na third line"
+ "Blabla\nBlabla\nBlabla\nBlabla\nBlabla\nBlabla\nBlabla\n"
+ "Blabla\nBlabla\nBlabla\nBlabla\nBlabla\nBlabla\n");
textArea.setSelectionColor(Color.RED);
frame.add(pane);
frame.setSize(300, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String turnToString = "Something else.\nA second line\na third line"
+ "Blabla\nBlabla\nBlabla\nBlabla\nBlabla";
final int pos = textArea.getText().indexOf(turnToString);
textArea.getHighlighter().addHighlight(pos,
pos + turnToString.length(),
new DefaultHighlighter.DefaultHighlightPainter(Color.yellow));
textArea.scrollRectToVisible(new Rectangle(0, 0, pane.getViewport().getWidth(), pane.getViewport().getHeight()));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
textArea.setCaretPosition(pos);
}
});
}
}