gpt4 book ai didi

java - 克隆整个 JTree/TreeModel 的最简单方法?

转载 作者:行者123 更新时间:2023-12-02 07:29:16 25 4
gpt4 key购买 nike

我真的必须自己实现深度克隆吗?或者是否有任何库方法可以获取 JTree 或其 TreeModel 的深度克隆?

最佳答案

正如@SteveKuo所说,为什么需要克隆TreeModelTreeModel 可以在 JTree 的不同实例之间共享。

这里是两个 JTree 共享同一模型的示例演示。或者,您可以创建两次相同的 TreeModel:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Test2JTree {

private void initUI() {
final JFrame frame = new JFrame(Test2JTree.class.getSimpleName());
final DefaultTreeModel model = getTreeModel();
final JTree tree1 = new JTree(model);
final JTree tree2 = new JTree(model);
frame.add(new JScrollPane(tree1), BorderLayout.WEST);
frame.add(new JScrollPane(tree2), BorderLayout.EAST);
frame.pack();
frame.setSize(frame.getWidth() + 50, frame.getHeight() + 140);
frame.setVisible(true);
Timer t = new Timer(2000, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.add(new DefaultMutableTreeNode("A new node"));
model.nodesWereInserted(root, new int[] { root.getChildCount() - 1 });
tree1.expandRow(0);
tree2.expandRow(0);
frame.revalidate();
}
});
t.start();
}

private DefaultTreeModel getTreeModel() {
return new DefaultTreeModel(new DefaultMutableTreeNode("Root object"));
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new Test2JTree().initUI();
}
});
}
}

关于java - 克隆整个 JTree/TreeModel 的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13142290/

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