Java 在 JFrame 上运行函数关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16372241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:32:27  来源:igfitidea点击:

Run function on JFrame close

javaswingjframewindowlistener

提问by Mattias

void terminate() {}
protected JFrame frame = new JFrame();

How can I get frameto run the terminate function when I press the close button?

frame当我按下关闭按钮时,如何运行终止功能?

Edit: I tried to run this, but for some reason it doesn't print test (however, the program closes). Does anyone have an idea what could be the problem?

编辑:我试图运行它,但由于某种原因它不打印测试(但是,程序关闭)。有谁知道可能是什么问题?

frame.addWindowListener(new WindowAdapter() {
    public void WindowClosing(WindowEvent e) {
        System.out.println("test");
        frame.dispose();
    }
});

采纳答案by Maroun

You can use addWindowListener:

您可以使用addWindowListener

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        // call terminate
    }
});

See void windowClosing(WindowEvent e)and Class WindowAdaptertoo.

参见void windowClosing(WindowEvent e)Class WindowAdapter

回答by Martin Seeler

If you want to terminate your program after the JFrame is closed, you have to set the default close operation on your JFrame.

如果要在 JFrame 关闭后终止程序,则必须在 JFrame 上设置默认关闭操作。

In your constructor of your JFrame write:

在你的 JFrame 的构造函数中写:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

If you just want to call a method when the window is closed and not terminate the whole program, than go with the answer of Maroun.

如果您只想在窗口关闭时调用一个方法而不是终止整个程序,那么请使用 Maroun 的答案。

回答by Gilbert Le Blanc

Not only do you have to add the window listener, you have to set the default close operation to do nothing on close. This allows your code to execute.

您不仅需要添加窗口侦听器,还必须将默认关闭操作设置为在关闭时不执行任何操作。这允许您的代码执行。

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent event) {
        exitProcedure();
    }
});

Finally, you have to call System exit to actually stop your program from running.

最后,您必须调用 System exit 以实际停止您的程序运行。

public void exitProcedure() {
    frame.dispose();
    System.exit(0);
}

回答by Muhammad

Frame.dispose() method does not terminate the program. To terminate the programe you need to call System.exit(0) method

Frame.dispose() 方法不会终止程序。要终止程序,您需要调用 System.exit(0) 方法