-1

I have this code here to create a key binding:

KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(k, k.toString());
getActionMap().put(k.toString(), new AbstractAction()
{ 
    public void actionPerformed(ActionEvent e)
    {
        //put action here
    }
});  

The problem is I have 8 of these across my program. Each of these creates a separate class file to hold the abstract class. How would I rewrite this, if possible, to limit the amount of classes created. (I have searched for this, but reduce abstract classes doesn't come up with anything useful)

Coupon22
  • 395
  • 8
  • 24

2 Answers2

5

In addition to extension, suggested here by @EdC, you can use composition, as shown in this example in which the Action uses parameters specified to the constructor of an enclosing JButton. Also, one Action can forward its ActionEvent to another Action, as shown in this KeyPadPanel.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    Good point. I would agree that its better to favor composition over inheritance. It really depends on exactly what the contents of these action providers are which would prove better in this case. – EdC Sep 15 '12 at 02:14
  • 1
    That second example is the example I used. I realized this problem was pointless and there doesn't seem to be a good way to reduce the number of classes. Your answer is the best answer, thank you. – Coupon22 Sep 15 '12 at 12:40
3

So what would help is if you update the question with perhaps some examples of where the duplication is. E.g. is it just the boiler plate of the anonymous inner class that's duplicated. If so you're stuck till java 8. Or is it that there is some significant portion of the method body that's duplicated?

In this case you could add an abstract super-class with the common code. This will actually increase the number of classes though which is not generally a problem. E.g.

private static abstract class MyBaseAction extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
        // Do Common Stuff
        // ....

        doSpecificStuff(e);
    }

    protected abstract void doSpecificStuff(ActionEvent e);
}

Then subclass this instead of abstract action for your anonymous inner class.

EdC
  • 2,309
  • 1
  • 17
  • 30