Java Reference
In-Depth Information
items. The first menu item will create a new window, while the second menu item will
destroy all windows. The beauty of the design is that a single event source, the menu item
for close all windows, will have multiple event listeners that are associated with it. When
the close all menu item is selected, all windows will be closed. Here is the implementation.
import java .awt . ;
import java .awt. event . ;
import java . util . ;
import javax . swing . ;
public class RandomWindows {
public static void main(String [] args)
{
MainFrame f = new MainFrame () ;
f . setVisible( true );
}
}
class MainFrame extends JFrame {
private static int counter = 0;
public MainFrame () {
setSize (200,200) ;
JMenuBar bar = new JMenuBar ( ) ;
setJMenuBar(bar ) ;
JMenu windowMenu = new JMenu( "Window" );
bar . add (windowMenu) ;
final JMenuItem newWindow = new JMenuItem( "New Window" );
final JMenuItem c l oseAl l = new JMenuItem( "Close All" );
windowMenu . add (newWindow) ;
windowMenu . add ( c l o s eA l l ) ;
newWindow. addActionListener( new ActionListener ()
{
public void actionPerformed(ActionEvent e) {
MyFrame f = new MyFrame( c l o s e A l l ) ;
f . setLocation(( int ) (Math . random ( ) 500) , ( int ) (Math . random ( )
500)) ;
f . setSize (200,200) ;
f . setVisible( true );
}
} );
}
}
class MyFrame extends JFrame {
public MyFrame( final JMenuItem c l oseAl l ) {
closeAll . addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
dispose() ;
}
} );
}
}
Note that the position of every new window is chosen randomly. Figure 10.3 shows how
the three event listeners are registered with the same event source. When the Close All
menu item is chosen, all three windows will be closed. Note that the menu item closeAll
is part of the window constructor. Every time a window is created, an ActionListener
is registered with the menu item closeAll . Therefore, if there are three windows, then
 
Search WWH ::




Custom Search