用JTree包装的单词

时间:2016-06-13 11:28:12

标签: java swing jtree word-wrap

我想知道是否有任何方法可以使用JTrees进行自动换行。我在节点的文本中使用HTML,我不确定这是否重要。

screenshot

1 个答案:

答案 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;
            }

        });

这给了我以下输出。

enter image description here

希望对你有所帮助。

对于自动换行的内容,您可以使用html

请参阅此link

中安德鲁的回答