Articles Projects Tips Downloads Contacts About

XMLEditorKit library as example of XML viewing in JEditorPane/JTextPane.

There are multiple XMLEditorKit implementations. Itís enough to google to find a few different ones. Thatís one more to represent XML content in JEditorPane. The XMLEditorKit extends StyledEditorKit and supports XML highlighting and tags folding. Itís based on read only XMLDocuemnt as a model and uses custom views to show tags and content. XMLReader which creates documentís structures uses JAXP DOM parser to read XML, iterates the obtained DOM and creates documentís Elements. The result looks like this:

Highlighing process uses 6 types of attributes which can be configured. See static fields of XMLDocument and initializing them.

    public static SimpleAttributeSet BRACKET_ATTRIBUTES=new SimpleAttributeSet();
    public static SimpleAttributeSet TAGNAME_ATTRIBUTES=new SimpleAttributeSet();
    public static SimpleAttributeSet ATTRIBUTENAME_ATTRIBUTES=new SimpleAttributeSet();
    public static SimpleAttributeSet ATTRIBUTEVALUE_ATTRIBUTES=new SimpleAttributeSet();
    public static SimpleAttributeSet PLAIN_ATTRIBUTES=new SimpleAttributeSet();
    public static SimpleAttributeSet COMMENT_ATTRIBUTES=new SimpleAttributeSet();
    static {
        StyleConstants.setBold(TAGNAME_ATTRIBUTES, true);
        StyleConstants.setForeground(TAGNAME_ATTRIBUTES, Color.GREEN.darker());
 
        StyleConstants.setBold(ATTRIBUTENAME_ATTRIBUTES, true);
 
        StyleConstants.setItalic(ATTRIBUTEVALUE_ATTRIBUTES, true);
        StyleConstants.setForeground(ATTRIBUTEVALUE_ATTRIBUTES, Color.BLUE);
 
        StyleConstants.setFontSize(PLAIN_ATTRIBUTES, StyleConstants.getFontSize(PLAIN_ATTRIBUTES)-1);
        StyleConstants.setForeground(PLAIN_ATTRIBUTES, Color.DARK_GRAY);
 
        StyleConstants.setFontSize(COMMENT_ATTRIBUTES, StyleConstants.getFontSize(COMMENT_ATTRIBUTES)-1);
        StyleConstants.setForeground(COMMENT_ATTRIBUTES, Color.GRAY);
        StyleConstants.setItalic(COMMENT_ATTRIBUTES, true);
    }

Indentation isnít based on font so any fonts and font sizes can be used in the attributes above. As it was mentioned above the XMLEditorKitís document is read only but copy and paste are supported. When something is copied algorithm changes selection to copy text of entire XML tag with content. So it can be pasted in the document. The content is inserted in the tag where caret is positioned.

To show XML file in JEditorPane use following code:

        JEditorPane editorPane=new JEditorPane();
        editorPane.setEditorKit(new XMLEditorKit());
        editorPane.read(new FileInputStream(pathToXMLFile));
        //or
        String xmlString=null;
        //some code to init the string
        editorPane.setText(xmlString);

Click here to get XMLEditorKit library. The source code is included in the .jar file (See src directory).

Mirror stanislavl.blogspot.com to discuss or post a comment.