gpt4 book ai didi

java - JDialog - 刷新 JTree 中动态添加的节点

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:29 29 4
gpt4 key购买 nike

我对用于 JDialog 的 JTree 节点可见性有疑问。当我想向模型添加新节点时,Jtree 没有刷新。

奇怪的是,如果我设置 setRootVisible(true),节点会按照它们应有的方式更新。

这是代码。提前致谢

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TestClass {

JTree tree;
DefaultTreeModel dm;
JDialog dialog;

public TestClass(){
JFrame frame = new JFrame("title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

JPanel showPane = new JPanel();
showPane.setLayout(new BorderLayout());

dm = new DefaultTreeModel(new DefaultMutableTreeNode("root"));
tree = new JTree(dm);
tree.setRootVisible(false);

JButton button = new JButton("add node");
button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent arg0) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
dm.insertNodeInto(new DefaultMutableTreeNode("Node " + (root.getChildCount() + 1)), root, root.getChildCount());

int c = root.getChildCount();
System.out.println("child count: " + c);

for(int i=0; i<c; i++){
DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
System.out.println("has node:" + node.getUserObject().toString());
}
}

});

showPane.add(tree, BorderLayout.CENTER);
showPane.add(button, BorderLayout.PAGE_END);

JComponent[] inputComponents = new JComponent[] {showPane};

Object[] opButtons = {"OK"};

JOptionPane optPane = new JOptionPane(inputComponents
, JOptionPane.PLAIN_MESSAGE
, JOptionPane.CLOSED_OPTION
, null
, opButtons
, opButtons[0]);

optPane.setPreferredSize(new Dimension(400 ,250));

dialog = optPane.createDialog(null, "Create new Application Node");
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);

if(optPane.getValue() != null){
System.exit(0);
}

}

public static void main(String arg[]){
TestClass myClass = new TestClass();
}

最佳答案

每次添加新的子节点时,确保从新节点的父节点到根节点展开路径:

DefaultMutableTreeNode newChild = new DefaultMutableTreeNode("Node " + (root.getChildCount() + 1));
dm.insertNodeInto(newChild, root, root.getChildCount());
tree.expandPath(new TreePath(dm.getPathToRoot(newChild.getParent())));

关于java - JDialog - 刷新 JTree 中动态添加的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876449/

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