Possible duplicate:How to programmatically close a JFrame
I am developing a java GUI using JFrame. I want to close the GUI frame and disable it through code. I 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 windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } });`
How can I raise a windowClosing event? Or is there some other way?
You need the following:
yourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You can add this line to the constructor (do not forget).
This will cause the window close event to fire programmatically:
topFrame.dispatchEvent(new WindowEvent(topFrame, WindowEvent.WINDOW_CLOSING));
If you want to close the frame, you need to call:
topFrame.dispose();
dispose()?
dispose()
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); } }