...
I want to highlight the current row of my JTextArea,
such as in the sourceeditor of Eclipse.
Does anybody know how I can do this?
Not with a JTextArea.
You should possibly use an JTextPane instead, or an own implementation of
JEditorPane.
Here's a stripped down version of an editor I wrote a couple of years ago...
//---------------------------------------
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
class JSyntaxArea
extends JEditorPane
{
StyledDocument document = null;
MutableAttributeSet defaultSyntax = new SimpleAttributeSet();
MutableAttributeSet highlightSyntax = new SimpleAttributeSet();
public JSyntaxArea ()
{
StyledEditorKit editorKit = new StyledEditorKit();
this.setEditorKit(editorKit);
document = (StyledDocument) this.getDocument();
// set colors for the different styles
StyleConstants.setBackground(highlightSyntax, Color.lightGray);
StyleConstants.setForeground(highlightSyntax, Color.RED);
StyleConstants.setBackground(defaultSyntax, Color.WHITE);
StyleConstants.setForeground(defaultSyntax, Color.BLACK);
}
private void setDefault()
{
int len = document.getLength();
String str = null;
document.setCharacterAttributes(0, len, defaultSyntax, false);
}
private void setHighlight (int offset, int len)
{
document.setCharacterAttributes(offset, len, highlightSyntax, false);
}
}
// Note, as it's a stripped down version, it may contain
// some bugs, even though I don't think so...
// Bjorn A