I am sorry if this is a n00b question, but I have spent way too long for this once I create the Window listener, window event, and everything else, how do I specify what method to invoke? Here is my code:
private static void mw() { Frame frm = new Frame("Hello Java"); WindowEvent we = new WindowEvent(frm, WindowEvent.WINDOW_CLOSED); WindowListener wl = null; wl.windowClosed(we); frm.addWindowListener(wl); TextField tf = new TextField(80); frm.add(tf); frm.pack(); frm.setVisible(true); }
I am trying to get a URL, and Download it, I have everything else worked out, I am just trying to get the window to close.
We can close the AWT Window or Frame by calling dispose() or System. exit() inside windowClosing() method. The windowClosing() method is found in WindowListener interface and WindowAdapter class.
public class WindowEvent extends ComponentEvent. A low-level event that indicates that a window has changed its status. This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window.
The close() method closes a window.
import java.awt.*; import java.awt.event.*; import javax.swing.*; class FrameByeBye { // The method we wish to call on exit. public static void showDialog(Component c) { JOptionPane.showMessageDialog(c, "Bye Bye!"); } public static void main(String[] args) { // creating/udpating Swing GUIs must be done on the EDT. SwingUtilities.invokeLater(new Runnable() { public void run() { final JFrame f = new JFrame("Say Bye Bye!"); // Swing's default behavior for JFrames is to hide them. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); f.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { showDialog(f); System.exit(0); } } ); f.setSize(300,200); f.setLocationByPlatform(true); f.setVisible(true); } }); } }
Also look into Runtime.addShutdownHook(Thread)
for any action that is vital to perform before shutting down.
Here is an AWT version of that code.
import java.awt.*; import java.awt.event.*; class FrameByeBye { // The method we wish to call on exit. public static void showMessage() { System.out.println("Bye Bye!"); } public static void main(String[] args) { Frame f = new Frame("Say Bye Bye!"); f.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { showMessage(); System.exit(0); } } ); f.setSize(300,200); f.setLocationByPlatform(true); f.setVisible(true); } }
This example shows how to use addWindowListener()
with a WindowAdapter
, a concrete implementation of the WindowListener
interface. See also, How to Write Window Listeners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With