Exemplo:
import java.awt.Color;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class HighlighEditor extends JFrame {
private class MeuStyledDocument extends DefaultStyledDocument {
private final AttributeSet palavraReservada;
private final AttributeSet palavraNormal;
public MeuStyledDocument() {
final StyleContext context = StyleContext.getDefaultStyleContext();
palavraReservada = context.addAttribute(context.getEmptySet(), StyleConstants.Foreground, Color.BLUE);
palavraNormal = context.addAttribute(context.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
}
@Override
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
super.insertString(offset, str, a);
highlight();
}
@Override
public void remove(int offs, int len) throws BadLocationException {
super.remove(offs, len);
highlight();
}
private void highlight() throws BadLocationException {
String text = getText(0, getLength());
String[] palavras = text.split("\\W");
int inicio = 0;
int fim = 0;
for (String palavra : palavras) {
inicio = text.indexOf(palavra, inicio);
fim = inicio + palavra.length();
AttributeSet estilo = RESERVADAS.contains(palavra) ? palavraReservada : palavraNormal;
setCharacterAttributes(inicio, fim, estilo, false);
inicio = fim + 1;
}
}
}
private static final List<String> RESERVADAS = Arrays.asList(
new String[] { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false",
"final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected",
"public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" });
public static void main(String args[]) {
try {
HighlighEditor editor = new HighlighEditor();
editor.setVisible(true);
} catch (Throwable t) {
t.printStackTrace();
}
}
public HighlighEditor() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
MeuStyledDocument document = new MeuStyledDocument();
JTextPane textPane = new JTextPane(document);
add(new JScrollPane(textPane));
}
}