This demo features a few interesting classes:
JavaFormatter
applies color-coded formatting to display Java source code.com.pump.io.parser.java.JavaParser
class.LineNumberBorder
paints the line number on the left side of the scrollpane.JTextPane textPane = new JTextPane(javaText); JScrollPane scrollPane = new JScrollPane(textPane); LineNumberBorder.install(scrollPane, textPane); new JavaFormatter(textPane);
Below is a screenshot:
The JavaFormatter
sets up a few SimpleAttributeSets
: defaultAttributes, keywordAttributes, errorAttributes, commentAttributes, stringAttributes, and importantPunctuationAttributes. (They're protected, and in theory you could create a subclass to customize them. Or add getters to modify them.)
The JavaParser
then parses a block of java source code, and the getAttributes(..)
method decides which AttributeSet to pair with a given token.
The LineNumberBorder
is a regular(-ish) javax.swing.Border
that is combined with the JScrollPane
's existing Border
using a CompoundBorder
. (If we put this border on the JTextComponent
: then the line number isn't visible when we scroll to the right.)
I've never tried to use this with a really large Java file, so I haven't focused on performance. If that use case ever comes up it might require some additional work. (Or in a worst-case scenario: it might require avoiding this class altogether if performance becomes a problem?)
This is similar to the XMLFormatter.