从另一个jframe向jtree添加节点

时间:2016-03-11 21:18:37

标签: java swing jframe jtree

如何在另一个textField中动态地(从jtree)节点添加到jframe? 这是我的小代码:

final First_JFRame frame= new First_JFRame();
DefaultTreeModel model = (DefaultTreeModel) frame.tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
          DefaultMutableTreeNode firstNode = new DefaultMutableTreeNode("firstNode") ;
          root.add(firstNode);
    firstNode.add(new DefaultMutableTreeNode("firstleaf"));
    firstNode.add(new DefaultMutableTreeNode("secondleaf"));
    model.reload(root);

知道jtree声明为公共静态

1 个答案:

答案 0 :(得分:1)

以下是如何获得所需操作的快速示例。 基本上你只需要将Jtree的实例传递给第二帧,然后再添加节点。

public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                JFrame frame1 = new JFrame();
                frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame1.setLocationRelativeTo(null);


                JTree tree = new JTree();
                DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                DefaultMutableTreeNode firstNode = new DefaultMutableTreeNode("firstNode") ;
                root.add(firstNode);
                firstNode.add(new DefaultMutableTreeNode("firstleaf"));
                firstNode.add(new DefaultMutableTreeNode("secondleaf"));
                model.reload();
                frame1.add(tree);
                frame1.pack();
                frame1.setVisible(true);

                JFrame frame2 = new JFrame();
                frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame2.setLocationRelativeTo(frame1);
                JTextField text = new JTextField(15);
                JButton add = new JButton("ADD");
                frame2.setLayout(new FlowLayout());
                frame2.add(text);
                frame2.add(add);
                frame2.pack();
                frame2.setVisible(true);

                add.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        firstNode.add(new DefaultMutableTreeNode(text.getText()));
                        model.reload();
                    }
                });
            }
        });

    }