No. an application with many open frames would only close the frame that contained the button (or it might do something completely different; it depends on the application.)
An event-handling program must
register its event listener with the component that generates the events
or with a container that holds that component.
With a JFrame
component, use
addWindowListener()
to register a listener.
Here is a complete GUI program, including the listener object.
The parts in blue are additions to the example program of the previous chapter:
import java.awt.*; import java.awt.event.*; import javax.swing.*; class myFrame extends JFrame { public void paint ( Graphics g ) { g.drawString("Click the close button", 10, 50 ); } } class WindowQuitter extends WindowAdapter { public void windowClosing( WindowEvent e ) { System.exit( 0 ); // what to do for this event } } public class GUItester { public static void main ( String[] args ) { myFrame frm = new myFrame(); // construct a myFrame object WindowQuitter wquit // construct a listener = new WindowQuitter(); // for the frame frm.addWindowListener( wquit ); // register the listener frm.setSize( 150, 100 ); frm.setVisible( true ); } }
Notice how the program registers the listener object with the event-generating GUI object. You can think of registering a listener object as establishing a channel of communication between the GUI object and the listener.