I am struggling with the ActionListener in Java in a parent class, I tried a bunch of possible solutions but could not get it work. This here also did not help: Java actionlistener actionPerformed in different class
The problem is as follows:
Class2 extends Class1, I have a button in Class2. As soon as the button in Class2 is pressed, Class1 should be notified through action listener and perform the event.
I'm struggling to let Class1 know that the event has happened. It looked pretty simple to me, but nevertheless I'm struggling.
Your help will be much apprechiated, thank you!
Parent Class
package test;
//imports removed for better visibility
public class ParentClass extends JPanel implements ActionListener{
JFrame frame;
public void createParentGui() {
frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel mainCard = new JPanel(new CardLayout(20, 20));
ChildClass card1 = new ChildClass();
mainCard.add(card1);
frame.add(mainCard, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Button pressed, action!");
}
}
Child Class
package test;
//imports removed for better visibility
public class ChildClass extends ParentClass {
ActionListener listener = null; //this is probably not right, how to do
//with a local variable when passing it to the parent class?
public Child() {
createGui();
}
private void createGui() {
final JButton b = new JButton("press me");
b.addActionListener(listener);
add(b);
}
}
ChildClass
has all of the fields and methods that ParentClass
does (in addition to its own unique fields and methods). This is how inheritance works.
So, since ParentClass
is an ActionListener
, that means that ChildClass
is too. More specifically, ChildClass
has inherited the public void actionPerformed(ActionEvent e)
method of ParentClass
.
Therefore, change b.addActionListener(listener);
to b.addActionListener(this)
. (you can also remove the listener
field of ChildClass
)
The new code will pass "this" ChildClass
object to b
, which will then call actionPerformed(ActionEvent e)
whenever the button is pressed. And since any ChildClass
object has the actionPerformed(ActionEvent e)
of ParentClass
, that means that ParentClass#actionPerformed(ActionEvent)
will be called (as you intended).