我用于 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();
}
}