简体   繁体   中英

Java: Cancel Button does not close the window for JFrame

I want the window to close when I press on Cancel button, but it's not working.

Code:

public class FirstClass{

private JFrame frame;
private JButton btnCancel;

public FirstClass() {

    frame = new JFrame("GRIIS Data Transfer [Mobile to PC]");
    frame.setBounds(200,200,900,450);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    btnCancel = new JButton("Cancel");
    btnCancel.setBounds(800, 5, 85, 25);

    frame.add(btnCancel);

    btnCancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    super.windowClosing(e);
                    System.exit(0);
                }
            });
        }

    });

}//end of constructor
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                FirstClass window = new FirstClass();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
}

Please let me know in case of changes needed in the code.

btnCancel.addActionListener()

so my code will work and close the application when I press on Cancel button.

Dont use window listner it gives event at time of closing, try

btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }});

No need to override WindowListener method,

public void actionPerformed(ActionEvent e) {
   System.exit(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM