Reputation:
I was wondering if there was any way to use word wrapping with JTrees. I am using HTML in the node's text, I'm not sure if that's important or not.
Upvotes: 3
Views: 840
Reputation: 1533
Ok you can try like below.
JTree tree = new JTree();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Animals");
DefaultTreeModel model = new DefaultTreeModel(root);
tree.setModel(model);
root.add(new DefaultMutableTreeNode(new Animal("Dog","ACS")));
root.add(new DefaultMutableTreeNode(new Animal("Cat","BCS")));
root.add(new DefaultMutableTreeNode(new Animal("Lion","FCS")));
root.add(new DefaultMutableTreeNode(new Animal("Tiger","<html>Hello World!<br>blahblahblah</html>")));
DefaultTreeSelectionModel sModel = new DefaultTreeSelectionModel();
sModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setSelectionModel(sModel);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent selection) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)selection.getPath().getLastPathComponent();
if(selectedNode.isLeaf()){
Animal animal = (Animal)selectedNode.getUserObject();
}
}
});
tree.setCellRenderer( new DefaultTreeCellRenderer(){
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if(value != null ){
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
if(node.isLeaf()){
Animal animal = (Animal)((DefaultMutableTreeNode)value).getUserObject();
this.setText(animal.name);
}else {
return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
}
}
return this;
}
});
This gives me below output.
Hope it help you.
For auto wrap the content you can use html
Please refer to Andrew's answer in this link
Upvotes: 3