I'm trying to extend JTextPane so that it styles different content "elements" (and can report what type of element the cursor is currently in). So that an xml tag would appear differently than content, or an attribute etc.
Do I need to extend DefaultStyledDocument, StyledEditorKit also? or is there a way use these to get the desired results?
I've recently been through this and got something to work very well. I have a custom XML document that contains data. Some elements of this data need to be represented in a different visual way from other elements on the textpane.
What I did was customize the styledDocument and made up some new styles to display for the different elements.
I have an xml content handler class that parses the xml document, and for each element that it encounters, it will insert that string onto the jtextpane (via the document.insertString() method) in a certain style depending on the XML tag that wrapped the content.
You need to have a good understanding of how the Document, EditorKit and Visual element (re JTextPane) interact before you will understand how to use them properly.
Let me know if you need some more guidence and I will post the basics back here.
Did you end up creating/extending your own editorkit?
No. Just used the standard one.
All I have done so far is make anything appearing between <ticker country="UK" isin="GB123456">company name</ticker> in my XML input appear as black text with a yellow background on the JTextPane. Any other elements just appear as normal black test. If I mouse over on this yellow part of the text, then I present a tooltip to the user that contains the attributes from that XML ticker element (this is solved in another way and not really related to the problem at hand).
So as I parse the XML content with a handler, in the endElement() method, I see what kind of element that I am dealing with. If it's a 'ticker' element, then I insert this text onto the editor with
The 'doc' is just a reference to my custom document object of the JTextPane(). The call to doc.getTickerStyle() returns an object that was created like:
This approach allows me to represent any XML element in a custom style made out of the properties available from the StyleConstants class.
I am not sure if this is similar to what you want to do, but the idea sounded similar.
I ended up overriding the insertString method in DefaultStyledDocument and parse each character as its going to figure out the formatting/color. Then I hacked together function to figure out what tag I'm currently inside by getting the carets current position and parsing backwards (well taking a quick step forward to the next ">"). It seems to work fairly quickly.