Organizing Actions in a Swing Application?

前端 未结 3 658
你的背包
你的背包 2021-01-02 18:03

My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.

3条回答
  •  梦毁少年i
    2021-01-02 18:40

    What I do is create a package (package tree actually) for action classes, then instantiate each class according to context. Almost all of my action classes are abstract with abstract methods to get the context (ala Spring).

    public abstract class CalcAndShowAction extends AbstractAction {
        //initialization code - setup icons, label, key shortcuts but not context.
    
        public void actionPerformed(ActionEvent e) {
            //abstract method since it needs ui context
            String data = getDataToCalc();
    
            //the actual action - implemented in this class, 
            //  along with any user interaction inherent to this action
            String result = calc(data);  
    
            //abstract method since it needs ui context
            putResultInUI(result);
        }
        //abstract methods, static helpers, etc...
    }
    
    //actual usage
    //...
    button.setAction(new CalcAndShowAction() {
        String getDataToCalc() {
            return textField.getText();
        }
    
        void putResultInUI(String result) {
            textField.setText(result);
        }
    });
    //...
    

    (sorry for any mistakes, I've written it by hand in this text box, not in an IDE).

提交回复
热议问题