更改TreeNode的名称而不更改userObject

时间:2015-12-06 12:43:00

标签: java swing jtree treenode

我有一个带有DefaultTreeModel的JTree和一些附加的DefaultMutableTreeNodes。
我正在寻找一种方法来更改节点的displayName,但我不想更改userObject,因为我需要它才能正确设置它。
此外,我不能简单地为我的userObject覆盖toString方法,因为我在我的代码中的其他位置使用toString,其中对此方法的相应更改将是不合适的。

所以问题是,是否可以用上述条件实现节点的重命名?

提前致谢
乌鸦

修改 一个小代码示例:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeNodeRenameExample extends JFrame {

    private JPanel  contentPane;
    private JTree tree;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TreeNodeRenameExample frame = new TreeNodeRenameExample();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TreeNodeRenameExample() {
        initGUI();
    }
    private void initGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        this.contentPane = new JPanel();
        this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(this.contentPane);
        {
            this.tree = new JTree();
            this.tree.setModel(new DefaultTreeModel(
                new DefaultMutableTreeNode("JTree") {
                    {
                        add(new DefaultMutableTreeNode(new testObj("Peter")));
                        add(new DefaultMutableTreeNode(new testObj("Stephen")));
                    }
                }
            ));
            this.contentPane.add(this.tree, BorderLayout.CENTER);
        }
    }

    public class testObj {
        private String name;

        public testObj(String name) {
            this.name = name;
        }

        public String toString() {
            return "Name: " + this.name;
        }
    }

}

我想要做的是将TreeNodes上的文本更改为不同的内容。例如,对于" MyTreeNode1"和" MyTreeNode2"但我想保留这两个节点的userObject我的testObj和toString mehtod也不能改变...

1 个答案:

答案 0 :(得分:1)

如果要对树用户对象使用TestObj类,并且不想更改toString方法,则可以使用自定义TreeNode类(而不是DefaultMutableTreeNode类)。使用此自定义类,可以覆盖toString方法,以便不(始终)使用用户对象,而是使用替代名称。

自定义TreeNode类可以例如被称为AliasTreeNode,并且可以在创建节点时或稍后在某些事件发生时接收别名(=替代节点名称)。 AliasTreeNode.toString方法检查是否设置了别名;如果存在别名,则返回该别名,否则返回DefaultMutableTreeNode.toString()

此代码的修改版本演示了该方法。节点在构造时获得别名,在按下按钮时获得不同的别名:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.*;

public class TreeNodeRenameExample extends JFrame {

    private JPanel  contentPane;
    private JTree tree;

    private AliasTreeNode peterNode = new AliasTreeNode(new TestObj("Peter"),
                                                        "Alias 1");
    private AliasTreeNode stephenNode = new AliasTreeNode(new TestObj("Stephen"),
                                                          "Alias 2");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TreeNodeRenameExample frame = new TreeNodeRenameExample();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TreeNodeRenameExample() {
        initGUI();
    }
    private void initGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        this.contentPane = new JPanel();
        this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(this.contentPane);
        {
            this.tree = new JTree();
            this.tree.setModel(new DefaultTreeModel(
                    new DefaultMutableTreeNode("JTree") {
                        {
                            add(peterNode);
                            add(stephenNode);
                        }
                    }
            ));
            this.contentPane.add(this.tree, BorderLayout.CENTER);

            JButton changeNamesButton = new JButton("Change node names");
            this.contentPane.add(changeNamesButton, BorderLayout.SOUTH);
            changeNamesButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    peterNode.setAlias("MyTreeNode1");
                    stephenNode.setAlias("MyTreeNode2");
                }
            });
        }
    }


    public class TestObj {
        private String name;

        public TestObj(String name) {
            this.name = name;
        }

        public String toString() {
            return "Name: " + this.name;
        }
    }


    public class AliasTreeNode extends DefaultMutableTreeNode {
        private String alias;

        public AliasTreeNode(Object userObject, String alias) {
            super(userObject);
            this.alias = alias;
        }

        public void setAlias(String alias) {
            this.alias = alias;

            // Notify the tree model of the changed node
            // (see http://stackoverflow.com/a/10375802/1694043).
            ((DefaultTreeModel) tree.getModel()).nodeChanged(this);
        }

        @Override
        public String toString() {
            return (alias != null) ? alias : super.toString();
        }
    }
}