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);
}
}
ChildClasshas all of the fields and methods thatParentClassdoes (in addition to its own unique fields and methods). This is how inheritance works.So, since
ParentClassis anActionListener, that means thatChildClassis too. More specifically,ChildClasshas inherited thepublic void actionPerformed(ActionEvent e)method ofParentClass.Therefore, change
b.addActionListener(listener);tob.addActionListener(this). (you can also remove thelistenerfield ofChildClass)The new code will pass "this"
ChildClassobject tob, which will then callactionPerformed(ActionEvent e)whenever the button is pressed. And since anyChildClassobject has theactionPerformed(ActionEvent e)ofParentClass, that means thatParentClass#actionPerformed(ActionEvent)will be called (as you intended).