Highlighting
a text in JTextArea (JAVA):
The following code shows you how you can color/highlight
the text in JTextArea, for example
all the java reserved words such as “public,
private, String” etc. and you want to highlight them in the JTextArea so you do the following:
First Creating a JTextArea:
JTextArea txtArea = new JTextArea();
Now, setting JTextArea size:
txtArea.setPreferredSize(new Dimension(790, 480));
The following String contains all the java
reserved words in it that we want to highlight in JTextArea:
String [] javaWords = {"abstract", "do", "import", "public", "throws", "boolean", "double", "instanceof", "return", "transient", "break", "else", " int ", "short","try", "byte", "extends", "interface", "static", "void", "case", "final", "long", "strictfp", "volatile", "catch", "finally", "native", "super", "while", "char", "float","new", "switch", "class", "for", "package", "synchronized", "continue", "if", "private","this", "default", "implements", "protected", "const", "goto", "null", "true", "false"};
The following function highLights function takes two
argumenst first JtextComponent and
the second String pattern:
// 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());
for (int i = 0; i < pattern.length; i++) {
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern[i],
pos)) >= 0) {
hilite.addHighlight(pos, pos
+ pattern[i].length(),
myHighlighter);
pos
+= pattern[i].length();
}
}
} catch (BadLocationException e) {}
}
The following function removeHighlight removes the highlight from the component:
// 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]);
}
}
}
Now how to call it in your application:
// An instance of the
private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlighter = new MyHighlightPainter(Color.LIGHT_GREY);
// A class of the default
highlight painter
private class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color
color) {
super(color);
}
}
Now, at keyPress/keyUp
event of interface KeyListener and
registered it with the JTextArea and
call the highLight function to color
the reserved words, like this:
txtArea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke)
{
highLight(txtArea,
javaWords);
}
});
0 comments:
Post a Comment