Uncertainties regarding Implementation of Actions and Usage of a single Model with multiple Views

前端 未结 3 889
死守一世寂寞
死守一世寂寞 2020-12-12 02:59

I\'m a total newbee regarding GUI programming and maybe my problem has a quite simple solution. I\'m trying to implement a Java Swing GUI that serves as an editor for a tree

3条回答
  •  独厮守ぢ
    2020-12-12 03:34

    A complete guide to application design in beyond the scope of Stackoverflow. Instead, start with the example TreeIconDemo shown in How to Use Trees. Notice how it adds a TreeSelectionListener to the tree in order to update a nearby JEditorPane. Now, add another TreeSelectionListener to a different view to see how you could update the new view, too. You might also get some insight from this related answer.

    Addendum: Starting from this example, you can do something like the following. Changing the selection updates the textField to show the selected node's name. Editing either the node (typically F2) or the textField changes the selected node's name.

    private JTextField textField = new JTextField(10);
    ...
    final DefaultTreeModel treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    tree.addTreeSelectionListener(new TreeSelectionListener() {
    
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getNewLeadSelectionPath();
            if (path != null) {
                DefaultMutableTreeNode node =
                    (DefaultMutableTreeNode) path.getLastPathComponent();
                if (node.isLeaf()) {
                    Resource user = (Resource) node.getUserObject();
                    textField.setText(user.toString());
                } else {
                    textField.setText("");
                }
            }
        }
    });
    textField.addActionListener(new AbstractAction("edit") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            TreePath path = tree.getSelectionPath();
            if (path != null) {
                DefaultMutableTreeNode node =
                    (DefaultMutableTreeNode) path.getLastPathComponent();
                if (node.isLeaf()) {
                    String s = textField.getText();
                    Resource user = (Resource) node.getUserObject();
                    user.setName(s);
                    treeModel.reload(node);
                }
            }
        }
    });
    

提交回复
热议问题