I'm making a code editor in java, and I ran into a problem while implementing syntax coluring. I could not find anything on the Internet on how to do it. I only found a 6 year old post that did not work. Can anyone help?
Asked
Active
Viewed 238 times
-1
-
Refer to this SO question: [How to change the color of specific words in a JTextPane?](https://stackoverflow.com/questions/14400946/how-to-change-the-color-of-specific-words-in-a-jtextpane) There is also this tutorial. [How to Use Editor Panes and Text Panes](https://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html) – Abra Sep 24 '20 at 14:48
-
that do not work for me – kristoffer gaming Sep 24 '20 at 15:00
-
(1-) What doesn't work for you? There are multiple answers. I picked one and it worked fine. Of course doing complete syntax coloring is a complex task since you need to handle comments and literals etc. – camickr Sep 24 '20 at 15:38
1 Answers
1
first: you need to use a jEditorPane
Second: Create a highlighter like this(you can change the color of the highligthe):
DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));
Third: to highlight use this
try {
jEditorPane1.getHighlighter().addHighlight("here put the number of the starting character", "Here put the ending number of character",
highlightPainter);
} catch (BadLocationException ex) {
}
Example.
JEditorPane text = new JEditorPane();
text.setText(" Hi This is example good");
DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 0, 0, 75));
try {
jEditorPane1.getHighlighter().addHighlight(3, 7, highlightPainter);
} catch (BadLocationException ex) {
}
It should apper this underlined: "i This ";

Holis
- 175
- 1
- 10