JavaFormatter Demo

JavaFormatter Demo

What Is It

This demo features a few interesting classes:

How To Use It

JTextPane textPane = new JTextPane(javaText);
JScrollPane scrollPane = new JScrollPane(textPane);
LineNumberBorder.install(scrollPane, textPane);
new JavaFormatter(textPane);

How It Looks

Below is a screenshot:

This is a screenshot of the JavaFormatterDemo

How It Works

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.)

Discussion

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.