答案 0 :(得分:2)
好的,你可以尝试如下。
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;
}
});
这给了我以下输出。
希望对你有所帮助。
对于自动换行的内容,您可以使用html
请参阅此link
中安德鲁的回答