编程语言
首页 > 编程语言> > java-用JTree进行文字包装

java-用JTree进行文字包装

作者:互联网

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

screenshot

解决方法:

好吧,您可以尝试如下.

        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中安德鲁的回答

标签:jtree,swing,word-wrap,java
来源: https://codeday.me/bug/20191118/2028927.html