简体   繁体   中英

How to minimize a jFrame when the window close button is pressed?

I want to minimize the JFrame when the close button is pressed, I am using the code shown below, but whenever I press the close button, the frame first minimizes and then closes automatically. I am working on Ubuntu.

How can I prevent the JFrame from closing?

public class MainClass {

    public static void main(String args[]) throws ClassNotFoundException {

        final Gui frame = new Gui();

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                frame.setExtendedState(Frame.ICONIFIED);
            }
        });

    }
}

Try maybe this way

final Gui frame = new Gui();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- prevent closing
frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        frame.setExtendedState(JFrame.ICONIFIED);
    }
});

frame.setSize(200,200);
frame.setVisible(true);

This will prevent window from closing, and your current code will minimize it (at least this is how it works on Win7, let me know if it helps or not).

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