javainheritanceactionlistener

How to add an ActionListener in the child class for a component in the parent class in java


I am programming a code editor in java and ran into a problem while trying to add an ActionListener to a button implemented in the parent class. The ActionListener implementation should be within the child class.

I have written the parent class DialogCreator and the child class ClassCreator this way.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class DialogCreator extends JFrame implements ActionListener {

    protected JButton buttonCancel;
    protected JDialog jDialog;

    public DialogCreator() {

         jDialog = new JDialog(this ,"title", true);  
         jDialog.setLayout(null);  
         jDialog.setSize(400,400);  
         
         buttonCancel = new JButton("Cancel");
         buttonCancel.setBounds(20,20,100,30);
        
         jDialog.add(buttonCancel);   
         jDialog.setVisible(true);
   
    }
    
    public void actionPerformed(ActionEvent e) {
    
    }
}
class ClassCreator extends DialogCreator{
    
    public ClassCreator(){
        
        super();
        buttonCancel.addActionListener((e)->jDialog.dispose());
         
    }
}
public class Main {

    public static void main(String[] args) {
        
        new ClassCreator();

    }

}

Program compiled successfully and I expected to close the jDialog when I click on Cancel button. But nothing happened. So can you tell me where I did wrong. The ClassCreator is parent to multiple child class in my code.


Solution

  • The mistake your making in your code is using super(). Remember that a JDialog waits until it gets a response before continuing. So your listener is added after you close the JDialog. So try using this instead:-

    ...
    public ClassCreator(){
        super();
        buttonCancel.addActionListener((e)-> jDialog.dispose());
        jDialog.setVisible(true);
    }
    ...
    

    Make sure you remove jDialog.setVisible from DialogCreator constructor.