Home > Mobile >  How to close a JFrame on a class that implements ActionListener
How to close a JFrame on a class that implements ActionListener

Time:10-09

I need to close a specific JFrame with another class that implements ActionListener

public class EditStudent extends JFrame {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    EditStudent frame = new EditStudent();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }); 
    }
}

I will use this class to a JButton on that JFrame. (It's like a controller to a JButton)

public class EditFileController implements ActionListener {
    @SuppressWarnings("unused")
    private JButton btnEdit = new JButton();

    public EditFileController(JButton btnEdit) {
        super();
        EditStudent.btnEdit = btnEdit;
    }
}

CodePudding user response:

Every searchable method. I've been searching for at least 5 hrs.

Well start with the basics of how to write an ActionListener. The code you posted doesn't even implement the actionPerformed(...) method so it won't even compile.

Read the Swing tutorial for Swing basics. Maybe start with the section on How to Use Lists. The ListDemo code shows how to use an inner class to define an ActionListener.

Your controller class makes no sense to me. You appear to be making it to complicated. For example why would you pass the button as a parameter but also make a new instance of the button in the class.

An ActionListener does NOT to define the button or have it passed as a parameter.

All you need to do is create the button where you add all other components to the frame. Then you add the ActionListener to your button.

Then the the basic code in your ActionListener would be:

Window window = SwingUtilities.windowForComponent(event.getSource());
window.dispose();

Once you get that working and understand the basic concepts you may want to check out Closing an Application which presents a simple API to create reusable code that can be used for any frame.

  • Related