Skip to content

Example: Hello, RSyntaxTextArea

bobbylight edited this page Sep 5, 2021 · 4 revisions

Example Usage

RSyntaxTextArea is simply a subclass of JTextComponent, so it can be dropped into any Swing application with ease.

import java.awt.*;
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;

/**
 * A simple example showing how to use RSyntaxTextArea to add Java syntax
 * highlighting to a Swing application.<p>
 *
 * This example uses RSyntaxTextArea 3.1.4.
 */
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(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setLocationByPlatform(true);

    }

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

}

Most of it is just Swing boilerplate.

An RSyntaxTextArea is the main text editor class. It extends JTextArea, so it has all the standard methods you'd expect from a Swing text component, plus more specific to handling syntax highlighting.

An RTextScrollPane is an extension of JScrollPane that supports line numbers, code folding, and other niceities. You can use a standard JScrollPane if you want, but when editing source code, it is often nice to have at least line numbering enabled.

RSyntaxTextArea knows about over 50 programming languages. To make the example highlight another language, simply change SyntaxConstants.SYNTAX_STYLE_JAVA to one of the other values defined in the SyntaxConstants class (current values can be seen here).