gpt4 book ai didi

java - 从另一个 jframe 添加节点到 jtree

转载 作者:行者123 更新时间:2023-12-01 10:15:01 26 4
gpt4 key购买 nike

如何动态添加(从 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声明为公共(public)静态

最佳答案

这是一个有关如何获得所需操作的快速示例。基本上,您只需将 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();
}
});
}
});

}

关于java - 从另一个 jframe 添加节点到 jtree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com