I wish to use processWindowEvent(..) to close the current window when I want to exit the program. But why cannot it work? ----------------------------------- import java.awt.*; import java.awt.event.*; public class Frame1 extends Frame { public static void main(String args[]){ new Frame1(); } /**Construct the frame*/ public Frame1() { setSize(300,400); show(); } /**Overridden so we can exit when window is closed*/ protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } }
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Because you aren't set up to listen for window events! Try this. It uses an anonymous class to catch the window closing event.
[This message has been edited by Thomas Paul (edited July 27, 2001).]
Thanks. But is there a way not to use WindowListener interface? Since from the book Java exam cram, it's said that override processEvent is another way to tackle event?
April.Johnson
Ranch Hand
Joined: May 02, 2001
Posts: 48
posted
0
Originally posted by david hu: Thanks. But is there a way not to use WindowListener interface? Since from the book Java exam cram, it's said that override processEvent is another way to tackle event?
You're right, David. From RHE, page 356:
The strategy of explicitly enabling events for a component can be summarized as follows: 1. Create a subclass of the component. 2. In the subclass constructor, call enableEvents(AWTEvent.XXX_EVENT_MASK). 3. Provide the subclass with a processXXXEvent() method; this method should call the superclass' version before returning.
You did 1 and 3, but forgot step 2. Add the following line in your constructor and you'll get the desired action. enableEvents(AWTEvent.WINDOW_EVENT_MASK); April [This message has been edited by April.Johnson (edited July 27, 2001).] [This message has been edited by April.Johnson (edited July 27, 2001).]
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
It is generally not recommended that you code that way. First because it is completely unneccessary since you can use the listener and second because you can cause serious problems if you forget to code: super.processWindowEvent(e); You should only use this technique when you absolutely have to do something before any other listener gets the event.