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

前端 未结 3 890
死守一世寂寞
死守一世寂寞 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:19

    Wow, that's a lot of detail! Thanks!

    Okay, I do something similar with JTable's (insert/delete rows).

    Essentially you want an Action that can take a reference to a JTree. This Action can then be supplied to your File menus, Popup Menus and event assigned to key strokes. If you write the code super efficiently, the same action can be shared, but this is not an essential requirement.

    What you want to do, is to let the view and model do what they are designed to do, you action is simply the catalyst for getting the process started.

    So basically you could do something like:

    public class RenameNodeAction extends AbstractAction {
    
        private JTree tree;
        public RenameNodeAction(JTree tree) {
            this.tree = tree;
    
            // Initialise action as you require...
        }
    
        // Access to the tree, provide mostly so you can extend the action
        public JTree getTree() {
            return tree;
        }
    
        public void actionPerformed(ActionEvent evt) {
    
            JTree tree = getTree();
            TreePath path = tree.getSelectionPath();
            if (path != null && tree.isPathEditable(path)) {
                tree.startEditingAtPath(path);
            }
    
        }
    }
    

    To make it a little more advanced, you could attach a TreeSelectionListener to the supplied tree and change the enabled state of the action based on the selection.

    So when nothing is selected, you would disable the action, if the selected wasn't editable, you would disable the selection, etc.

    What this means (as you have correctly trying to achieve) is that the code to achieve this is centralised and reusable. You can apply the same action (the same instance or multiple instances) to File menus, tool bar buttons, JButtons, popup menus and key strokes and be assured that the same code is executing for each.

提交回复
热议问题