Search code examples
javaswingjbuttonactionlistenerextends

How to extend actionPerformed method when extending a JButton class


If I have class A which extends JButton and implements ActionListener and it performs a certain default action. Then I have class B which extends class A and I want it to do the same action, plus something else. How do I go about extending the class A's actionPerformed method?

Class A:

class AButton extends JButton implements ActionListener {
    AButton () {
        addActionListener(this);
    }
    @Override
    public void actionPerformed (ActionEvent aEvent) {
        methodA();
    }
}

Class B:

class BButton extends AButton {
    BButton () {
        super();
        addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent aEvent) {
               methodB();
           } 
        });
    }
}

Solution

  • You can override methodA() rather than actionPerformed() call

    protected void methodA() {
      super.methodA();
      //additional actions here
    }