How do I organize my Actions in Swing?

做~自己de王妃 提交于 2019-11-26 23:25:38

问题


I am currently replacing my anonymous ActionListeners

new ActionListener() {
    @Override
    public void actionPerformed(final ActionEvent event) {
        // ...
    }
}

with class files representing actions:

public class xxxxxxxAction extends AbstractAction {
}

However, my GUI is able to perform a lot of actions (eg. CreatePersonAction, RenamePersonAction, DeletePersonAction, SwapPeopleAction, etc.).

Is there a good way to organize these classes into some coherent structure?


回答1:


You can keep your actions in a separate package to isolate them. Sometimes, it is useful to keep them in one class, especially if actions are related or have a common parent, for example:

public class SomeActions {
    static class SomeActionX extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    }

    static class SomeActionY extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    }

    static class SomeActionZ extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    }
}

Then to access them:

JButton button = new JButton();
button.setAction(new SomeActions.SomeActionX());



回答2:


I'm just feeling the strain of converting ~60 ActionListeners into separate classes.

Only you can decide if 60 is minimal. This example uses four instances of a single class. StyledEditorKit, seen here, is a good example if grouping as a series of static factory methods. The example cited here uses nested classes. JHotDraw, cited here, generates suitable actions dynamically.




回答3:


First of all you should provide public methods for all actionPerformed used in your actions (createPerson, removePerson, etc.). All these action methods should be in one class (I call it PersonController). Than you need to define your AbstractPersonAction:

public class AbstractPersonAction extends AbstractAction {
  private PersonController controller;

  public AbstractPersonAction(PersonController aController) {
    controller = aController;
  }

  protected PersonController getContrller() {
    return controller;
  }
}

Now you can extract all your actions into separate classes.

public class CreatePersonAction extends AbstractPersonAction {

  public CreatePersonAction(PersonController aController) {
    super(controller);
  }

  public void actionPerformed(ActionEvent ae) {
    getController().createPerson();
  }
}

These actions can be a part of an outer class or be placed in separate "actions" package.



来源:https://stackoverflow.com/questions/14736792/how-do-i-organize-my-actions-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!