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

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

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

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

4 回答 4

25

您可以使用addWindowListener

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

参见void windowClosing(WindowEvent e)Class WindowAdapter

于 2013-05-04T08:29:46.840 回答
20

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.

public void exitProcedure() {
    frame.dispose();
    System.exit(0);
}
于 2013-05-04T09:41:53.517 回答
2

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

于 2014-11-18T16:15:31.577 回答
1

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

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

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

于 2013-05-04T09:07:04.070 回答