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?
-
Refer to this SO question: How to change the color of specific words in a JTextPane? There is also this tutorial. How to Use Editor Panes and Text Panes– AbraCommented Sep 24, 2020 at 14:48
-
1that do not work for me– kristoffer gamingCommented Sep 24, 2020 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.– camickrCommented Sep 24, 2020 at 15:38
Add a comment
|
1 Answer
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 ";