Adv Java - [Swing: Menu]

♠ Posted by Unknown in at 00:09

Java Swing Menus


Each component capable of holding a menu, including JApplet, JFrame, JDialog, and their descendants, has a setJMenuBar() method that accepts a JMenuBar (you can have only one JMenuBar on a particular component). you add JMenu to the JMenuBar,  and JMenuItems to the JMenu. Each JMenuItem can have an ActionListener attached to it, to be fired when that menu item is selected.


Example:

/* <APPLET CODE = "MenuExample.CLASS" WIDTH = 500 HEIGHT = 500></APPLET>
 */
 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
public class MenuExample extends JApplet
{
          String [] flavors = { "Chocolate", "Strawberry", "Vanilla", "Mint", "Mocha" ,"Rum" , "Praline"};
          JTextField t = new JTextField("No flavor" , 30);
          JMenuBar mb1 = new JMenuBar();
          JMenu f = new JMenu("File"), m = new JMenu("Flavors"), s = new JMenu("Safety");
         
          JCheckBoxMenuItem [] safety = {new JCheckBoxMenuItem("Guard"),
                                                          new JCheckBoxMenuItem("Hide")};
         
          JMenuItem [] file = {new JMenuItem("Open")};
         
          JMenuBar mb2 = new JMenuBar();
          JMenu fooBar = new JMenu("Foor Bar");
          JMenuItem[] other = {new JMenuItem("Foo", KeyEvent.VK_F), new JMenuItem("Bar",KeyEvent.VK_B), new JMenuItem("Baz")};
          JButton jb = new JButton("Swap Menus");
         
          public void init()
          {
                   for(int i = 0; i< flavors.length; i++)
                   {
                             JMenuItem mi = new JMenuItem(flavors[i]);
                             m.add(mi);
                             if((i + 1) % 3 == 0)
                                      m.addSeparator();

                   }
                  
                   for(int i = 0; i < safety.length; i++)
                             s.add(safety[i]);
Image: Swing Menu Example                   s.setMnemonic(KeyEvent.VK_A);
                   f.add(s);
                   f.setMnemonic(KeyEvent.VK_F);
                  
                   for(int i = 0; i < file.length; i++)
                   {
                             f.add(file[i]);
                   }
                  
                   mb1.add(f);
                   mb1.add(m);
                   setJMenuBar(mb1);
                   t.setEditable(false);
                  
                   Container contentPane = getContentPane();
                   contentPane.add(t, BorderLayout.CENTER);
                   jb.setMnemonic(KeyEvent.VK_S);
                  
                   contentPane.add(jb, BorderLayout.NORTH);
                  
                   for(int i = 0; i < other.length; i++)
                             fooBar.add(other[i]);
                   fooBar.setMnemonic(KeyEvent.VK_B);
                   mb2.add(fooBar);
                  
          }

}


0 comments:

Post a Comment