I have a simple Jython GUI that displays an XML file in a JTree. Is there a method I can override in the tree model that will allow me to customize what the nodes in the JTree are called? Or do I need to do something with a renderer like Java? I’m looking for a Jythonic way to do this (as opposed to straight Java) if possible. I have access to Jython 2.5.0. My simple code looks like this:
from java import awt
from javax import swing
from java.lang import System
from xml.etree import ElementTree
class XmlTreeModel(swing.tree.TreeModel):
def __init__(self, etree):
self.etree = etree
def getRoot(self):
return self.etree.getroot()
def getChildCount(self, object):
return len(object)
def getChild(self, parent, index):
return parent[index]
class Viewer(swing.JFrame):
def __init__(self):
super(Viewer, self).__init__()
def display(self, fileName):
xmlObject = ElementTree.parse(fileName)
xmlTreeModel = XmlTreeModel(xmlObject)
jTree = swing.JTree(xmlTreeModel)
self.contentPane.add(jTree)
self.contentPane.setPreferredSize( awt.Dimension(100, 200) )
self.pack()
self.setDefaultCloseOperation(swing.JFrame.EXIT_ON_CLOSE)
self.setLocationRelativeTo(None)
self.setVisible(True)
if __name__ == "__main__":
viewer = Viewer()
viewer.display('my.xml')
Right now the nodes appear as <Element Category at 2> and I’d like to change them to just say “Category” or even better, something custom from the XML attributes.
EDIT:
I was able to extend Chui Tey’s answer so that my tree displays an XML attribute by changing DisplayNode slightly:
class DisplayNode(object):
def __init__(self, node):
self.node = node
def __repr__(self):
return self.node.get('Name')
def __getitem__(self, item):
return self.node[item]
def __len__(self):
return len(self.node)
Instances of the class are then created with DisplayNode(self.etree.getroot()) and DisplayNode(parent[index]), respectively. For those of you arriving via search engine, this works for me because I know all of my XML nodes will have an attribute called Name.
JTree calls repr(node) on each xml node to get a string representation of what to display on the leaves of its tree.
You can override it by supplying your own repr method.
In the example below, I have set the value manually in the displaytext attribute.