java 使用代码关闭java框架

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5830256/
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-10-30 13:00:09  来源:igfitidea点击:

close java frame using code

javaeventsswingjframe

提问by user673218

Possible Duplicate:
How to programmatically close a JFrame

可能的重复:
如何以编程方式关闭 JFrame

I am developing a java GUI using JFrame. I want to close the GUI frame and dispose it off through code. I have implemented :

我正在使用 JFrame 开发 Java GUI。我想关闭 GUI 框架并通过代码处理它。我已经实施:

topFrame.addWindowListener(new WindowListener()
        {
            public void windowClosing(WindowEvent e)
            {
                emsClient.close();
            }
            public void windowOpened(WindowEvent e) {
            }
            public void windowClosed(WindowEvent e) {
            }
            public void windowIconified(WindowEvent e) {
            }
            public void windowDeiconified(WindowEvent e) {
            }
            public void windowActivated(WindowEvent e) {
            }
            public void windowDeactivated(WindowEvent e) {
            }
        });`

How can I invoke the windowClosing event?? Or is there some other way?

如何调用 windowClosing 事件?或者有其他方法吗?

采纳答案by sfrj

You need this:

你需要这个:

yourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

You can add that line in the constructor(Dont forget it).

您可以在构造函数中添加该行(不要忘记)。

回答by WhiteFang34

This will programmatically trigger the window closing event:

这将以编程方式触发窗口关闭事件:

topFrame.dispatchEvent(new WindowEvent(topFrame, WindowEvent.WINDOW_CLOSING));

If you want to close the frame you need to call:

如果要关闭框架,则需要调用:

topFrame.dispose();

回答by Lukasz

How about invoking dispose()method?

调用dispose()方法呢?

回答by Andrew Thompson

import java.awt.event.*;
import javax.swing.*;

class CloseFrame {

    public static void main(String[] args) {

        Runnable r = new Runnable() {

            public void run() {
                JButton close = new JButton("Close me programmatically");
                final JFrame f = new JFrame("Close Me");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setContentPane( close );
                close.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        // make the app. end (programatically)
                        f.dispose();
                    }
                } );
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };

        SwingUtilities.invokeLater(r);
    }
}