我有一个JTree
和一个JTextField
。当我在树上选择一个节点时,文本字段将显示该节点的值。然后我可以编辑文本并保存它以更改所选节点的值。我使用DefaultTreeModel
'nodeChanged
方法来更新树。
这是告诉树模型更新其节点的正确方法吗?对我来说它看起来很丑,因为我明确地访问了树的模型并告诉它发生了一些事情。
这是一些代码
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class TextPaneTest extends JFrame {
private JTextField textBox = null;
private JTree tree = null;
private JButton button = null;
public static void main(String args[]) {
new TextPaneTest();
}
public TextPaneTest() {
// Main panel
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Panel holding tree
JPanel treePanel = new JPanel();
treePanel.setLayout(new BorderLayout());
// Panel holding text field and button
JPanel editPanel = new JPanel();
editPanel.setLayout(new BorderLayout());
// My textbox
textBox = new JTextField();
// button
button = new JButton();
button.setText("Save changes");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
String text = textBox.getText();
node.setUserObject(text);
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
model.nodeChanged(node);
}
});
// My Tree
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root");
tree = new JTree(top);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
textBox.setText(node.getUserObject().toString());
}
});
JScrollPane scrollPane = new JScrollPane(tree);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// Add tree
treePanel.add(scrollPane);
panel.add(treePanel, BorderLayout.CENTER);
// Add box and button to edit panel
editPanel.add(textBox, BorderLayout.CENTER);
editPanel.add(button, BorderLayout.SOUTH);
// Add edit panel
panel.add(editPanel, BorderLayout.SOUTH);
// Add everything to the frame
this.add(panel);
this.setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}