Search code examples
javaswingcode-editor

how can i implement syntax coloring on a jtextpane


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?


Solution

  • 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 ";