JTextArea textComp = new JTextArea();
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter;
//Einzeilige Komentare
myHighlightPainter = new MyHighlightPainter(Color.blue);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, "//")) >= 0)
{
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, textComp.getLineEndOffset(textComp.getLineOfOffset(pos) , myHighlightPainter);
pos = textComp.getLineEndOffset(textComp.getLineOfOffset(pos);
}
} catch (BadLocationException e){}
//headword Gruppe 1 highlighten
String[] headword = {"public", "private","static","final","try","catch","final","for","while","if","else"};
myHighlightPainter = new MyHighlightPainter(Color.red);
for(int i=0; i<headwords.lenth; i++)
{
// Highlight the occurrences of the word headword[i]
highlight(textComp, headword[i]);
}
//headword Gruppe 2 highlighten
headword = {"int","double","byte","float","byte","short","long","char","boolean","String"};
myHighlightPainter = new MyHighlightPainter(Color.green);
for(int i=0; i<headwords.lenth; i++)
{
// Highlight the occurrences of the word headword[i]
highlight(textComp, headword[i]);
}
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
//removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i=0; i<hilites.length; i++) {
if (hilites[i].getPainter() instanceof MyHighlightPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}