XMLFormatter Demo

XMLFormatter Demo

What Is It

This demo features a few interesting classes:

How To Use It

JTextPane textPane = new JTextPane(xmlText);
JScrollPane scrollPane = new JScrollPane(textPane);
LineNumberBorder.install(scrollPane, textPane);
new XMLFormatter(textPane);

How It Looks

Below is a screenshot:

This is a screenshot of the XMLFormatterDemo

How It Works

The XMLFormatter sets up a few SimpleAttributeSets: defaultAttributes, elementNameAttributes, 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 XMLParser then parses a block of XML, 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

This project's XMLParser class is not intended to be a fully-functional XML parser. It supports what I call "everyday XML". And maybe I'll scale it up as needed, or you can swap it out with something else as needed. (I did experiment with a couple of existing parsers, but I found they didn't give me the exact positions of each token. If anyone has any leads for an XML parser that I should try, please let me know!)

Also I've never tried to use this with a really large XML 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 JavaFormatter.