MenuDemo.java

Download MenuDemo.java

 1: // This program creates a simple Frame with a menu, with a
 2: // couple of menu items in it.  A listener is added to the
 3: // menu as well as to one of the items.  This shows which
 4: // listener gets invoked.
 5: //
 6: // Written 12/2009 by Wayne Pollock, Tampa Florida USA
 7: 
 8: import java.awt.event.*;
 9: import javax.swing.*;
10: 
11: public class MenuDemo extends JFrame
12: {
13:    public static void main ( String [] args )
14:    {
15:       JFrame f = new MenuDemo( "Menu Demo" );
16:       f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
17:       f.setSize( 550, 300 );
18:       f.setVisible( true );
19:    }
20: 
21:    public MenuDemo ( String title )
22:    {
23:       super( title );
24:       JMenu file = new JMenu( "File" );
25:       file.setMnemonic( 'F' );  // So ALT+F activates menu
26: 
27:       JMenu fruit = new JMenu( "Fruit" );
28:       fruit.setMnemonic( 'r' );
29: 
30:       JMenuItem apple = new JMenuItem( "Apple" );
31:       apple.setMnemonic( 'A' );
32:       fruit.add( apple );
33: 
34:       JMenuItem pear = new JMenuItem( "Pear" );
35:       pear.setMnemonic( 'P' );
36:       // For AWT, use Menuitem.setShortcut() method instead:
37:       pear.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK) );
38:       fruit.add( pear );
39: 
40:       fruit.addSeparator();
41: 
42:       JMenuItem mango = new JMenuItem( "Mango" );
43:       mango.setMnemonic( 'M' );
44:       fruit.add( mango );
45: 
46:       JMenuItem quit = new JMenuItem( "Quit" );
47:       quit.setMnemonic( 'Q' );
48:       quit.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK) );
49:       file.add( quit );
50: 
51:       JMenuBar bar = new JMenuBar();
52:       setJMenuBar( bar );
53:       bar.add( file );
54:       bar.add( fruit );
55: 
56:       // Hook up event handling:
57: 
58:       quit.addActionListener( new ActionListener()
59:        {
60:          public void actionPerformed ( ActionEvent ae )
61:          {
62:             System.exit( 0 );
63:          }
64:        }
65:       );
66: 
67:       pear.addActionListener( new ActionListener()
68:        {
69:          public void actionPerformed ( ActionEvent ae )
70:          {
71:             JOptionPane.showMessageDialog( null, "You selected a pear." );
72:          }
73:        }
74:       );
75: 
76:       // This does nothing; listeners must be on the items:
77:       fruit.addActionListener( new ActionListener()
78:        {
79:          public void actionPerformed ( ActionEvent ae )
80:          {
81:             JOptionPane.showMessageDialog( null, "You selected a non-pear." );
82:          }
83:        }
84:       );
85:    }
86: }