How do I organize my actions in Swing?

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 capable of doing a lot of things (like CreatePersonAction, RenamePersonAction, DeletePersonAction, SwapPeopleAction, etc.).

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

+3


source to share


3 answers


You can save your activities in a separate package to isolate them. It is sometimes useful to keep them in the same class, especially if the activities 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());

      

+8


source


I just feel the tension of converting ~ 60 ActionListeners into separate classes.



Only you can decide if it is minimal 60

. This example uses four instances of the same class. StyledEditorKit

seen here is a good example when grouped as a series of static factory methods . In the example shown here nested classes are used. JHotDraw

, cited here , dynamically generates the appropriate actions.

+6


source


First of all, you must provide public methods for all actionPerformed used in your actions (createPerson, removePerson, etc.). All of these action methods should be in the same 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 of your activities 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 part of an outer class, or they can be placed in a separate action package.

+3


source







All Articles