开发者

close java frame using code [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to programmatically close a 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 :

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 windo开发者_如何学运维wActivated(WindowEvent e) {
            }
            public void windowDeactivated(WindowEvent e) {
            }
        });`

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


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();


How about invoking dispose() method?


You need this:

yourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜