How do I colorise certain words in JTextPane?

101 views Asked by At

I have a simple HTML text Editor which I'm trying to convert into an IDE. I'm finished with the basics (Like adding a file browser and running the project). The next obstacle I'm facing is adding themes.

I googled and found this question but it requires adding the text before changing its color.
What behaviour I want is similar to JetBrains Webstorm (Or IntelliJ IDE): enter image description here

This is what it looks like as of now: enter image description here

1

There are 1 answers

6
Arsh Coder On BEST ANSWER

Like @MadProgrammer mentioned, you can use RSyntaxTextArea.

From its README:

RSyntaxTextArea is a customizable, syntax highlighting text component for Java Swing applications. Out of the box, it supports syntax highlighting for 50+ programming languages, code folding, search and replace, and has add-on libraries for code completion and spell checking. Syntax highlighting for additional languages can be added via tools such as JFlex.

Example Usage:-

import javax.swing.*;
import java.awt.BorderLayout;

import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;

public class TextEditorDemo extends JFrame {

    public TextEditorDemo() {

        JPanel cp = new JPanel(new BorderLayout());

        RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60);
        textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
        textArea.setCodeFoldingEnabled(true);
        RTextScrollPane sp = new RTextScrollPane(textArea);
        cp.add(sp);

        setContentPane(cp);
        setTitle("Text Editor Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);

    }

    public static void main(String[] args) {
        // Start all Swing applications on the EDT.
        SwingUtilities.invokeLater(() -> new TextEditorDemo().setVisible(true));
    }

}