tutorial on using Java to write graphical menus _java

Source: Internet
Author: User

There are two types of menus: drop-down menus and pop-up menus. This chapter only discusses the Drop-down menu programming method. Menus are different from JComboBox and Jcheckbox, and they are always visible in the interface. The menu is the same as JComboBox, where only one item can be selected at a time.

Selecting an option in the Drop-down menu or pop-up menu produces a ActionEvent event. The event is sent to the monitor for that option, and the meaning of the event is explained by the Monitor.
menu, menus, and menu items

The Drop-down menu is visualized by the name appearing on the menu bar, and the menu bar (jmenubar) usually appears at the top of the JFrame, and a menu bar displays the names of multiple drop-down menus. You can activate the Drop-down menu in two ways. One is to press the mouse button, and keep down the state, move the mouse until the release of the mouse to complete the selection, high-brightness display menu item is selected. Alternatively, when the cursor is over the menu name in the menu bar, click the mouse, in which case the menu expands and the menu item is displayed with high brightness.

A menu bar can have multiple menus (jmenu), and each menu can have many menu items (jmenuitem). For example, the menu bar for the Eclipse Environment has a menu of file, Edit, Source, Refactor, and many menu items for each menu. For example, the File menu has a menu item such as new, Open file, close, close, and all.

Add a menu to a window by first creating a menu bar object, then creating several menu objects, putting the menu objects in the menu bar, and then adding menu items to each menu object as required.
menu items in menus can also be a complete menu. Because a menu item can be another complete menu, you can construct a hierarchical menu structure.

1. Menu bar
the instance of Class JMenuBar is the menu bar. For example, the following code creates a menu bar object menubar:

  JMenuBar menubar = new JMenuBar ();


To add a menu bar to a window, you must use the Setjmenubar () method in the JFrame class. For example, code:

  Setjmenubar (menubar);

The common methods for class JMenuBar are:

    • Add (jmenu m): Adds menu m to the menu bar.
    • Countjmenus (): Gets the number of menu bars in the menu bar.
    • Getjmenu (int p): Gets the menu in the menu bar.
    • Remove (jmenu m): Removes the menu m from the menu bar.

2. Menu
The object created by the class JMenu is the menu. The common methods for class JMenu are as follows:

    • JMenu (): Creates a menu of empty headers.
    • JMenu (String s): Creates a menu titled S.
    • Add (JMenuItem Item): Adds menu options specified by the parameter item to the menu.
    • Add (JMenu menu): Adds a menu specified by the parameter menu to the menu. Implements the submenu embedded in the menu.
    • AddSeparator (): Draws a divider line between menu options.
    • GetItem (int n): Gets the menu item at the specified index.
    • GetItemCount (): Gets the number of menu items.
    • Insert (JMenuItem item,int N): In the position of the menu N Insert menu item item.
    • Remove (int N): menu item that deletes the location n
    • RemoveAll (): Deletes all menu items from the menu.

3. Menu items
An instance of a class JMenuItem is a menu item. The common methods for class JMenuItem are as follows:

    • JMenuItem (): Constructs a menu item without a caption.
    • JMenuItem (String s): Constructs a caption menu item.
    • SetEnabled (Boolean B): Sets whether the current item can be selected.
    • IsEnabled (): Returns whether the current menu item can be selected by the user.
    • Getlabel (): Gets the name of the menu item.
    • SetLabel (): Sets the name of the menu option.
    • addActionListener (ActionListener E): Sets the monitor for the menu item. The monitor accepts action events that click on a menu.

4. Handling Menu Events
The event source for the menu is to click a menu item with the mouse. The interface that handles the event is ActionListener, and the interface method to implement is actionperformed (ActionEvent e), which obtains the method GetSource () of the event source.

The example Small application schematic window has the implementation method of the menu bar. Has a button, when the button is in the Open window state, the Click button will open a window, the window has a menu bar, there are two menus, each menu has three items. When a menu item is selected, the menu item watch method displays the selected word in the text box.

Import java.applet.* import javax.swing.*;
Import java.awt.*;
Import java.awt.event.*;
  Class Menuwindow extends JFrame implements actionlistener{public static JTextField text;
    private void AddItem (JMenu menu,string Menuname,actionlistener listener) {JMenuItem Anitem = new JMenuItem (menuName);
    Anitem.setactioncommand (MenuName);
    Anitem.addactionlistener (listener);
  Menu.add (Anitem);
    Public Menuwindow (String s,int w,int h) {settitle (s);
    Container con = This.getcontentpane ();
    Con.setlayout (New BorderLayout ());
    This.setlocation (100,100);
    This.setsize (W,H);
    JMenu menu1 = new JMenu ("Sport");
    AddItem (menu1, "running", this);
    AddItem (menu1, "skipping", this);
    AddItem (menu1, "play", this);
    JMenu menu2 = JMenu ("entertainment");
    AddItem (MENU2, "singing", this);
    AddItem (MENU2, "Dance", this);
    AddItem (MENU2, "game", this);
    JMenuBar menubar = new JMenuBar ();
    Text = new JTextField ();
    Menubar.add (MENU1);
    Menubar.add (MENU2);
    Setjmenubar (MenuBar); COn.add (Text,borderlayout.north);
public void actionperformed (ActionEvent e) {text.settext (E.getactioncommand () + "menu item is selected!");}
  public class Example6_5 extends Applet implements actionlistener{Menuwindow window;
  JButton button;
  Boolean BFLG;
    public void init () {button = new JButton ("Open My sports entertainment window"); Bflg =true;
    window = new Menuwindow ("Sports Entertainment Window", 100,100);
    Button.addactionlistener (this);
  Add (button); } public void actionperformed (ActionEvent e) {if (E.getsource () ==button) {if (BFLG) {window.setvisible (t
        Rue);
        BFLG = false;
      Button.setlabel ("Close My sports entertainment window");
        } else{Window.setvisible (false);
        BFLG = true;
      Button.setlabel ("Open My sports entertainment window");
 }
    }
  }
}

5. Embed submenu
Creates a menu and creates multiple menu items with a menu item that is a menu (with other menu items), which constitutes a menu nesting. For example, change the relevant code in the above program to the following:

  Menu menu1,menu2,item4;
  MenuItem item3,item5,item6,item41,item42;


Insert the following code to create the Item41 and ITEM42 menu items and add them to the Item4 menu:

  item41= new MenuItem ("Dongfanghong");
  ITEM42 = new MenuItem ("peony");
  Item4.add (ITEM41);
  Item4.add (ITEM42);


When you click on the Item4 menu, you will open two items to choose from.

6. Add Exit entry to Menu
Adding a new menu item, adding Monitoring to the menu item, and using the System.exit () method in the corresponding monitoring method, enables you to exit the Java Runtime Environment when you click the menu item. For example, the following schematic code:


... Item7 = new MenuItem ("Exit");
Item7.addactionlistener (this);
... public void actionperformed (ActionEvent e) {
if (E.getsource () ==item7) {
system.exit (0);
}
}


7. Set shortcut keys for menu items
Use the Menushortcut class to set shortcut keys for menu items. The construction method is menushortcut (int key). Where key can take value keyevent.vk_a to Kenevent.vk_z, also can take ' a ' to ' Z ' key code value. Menu items Use the Setshortcut (menushortcut K) method to set shortcut keys. For example, the following code sets the letter E as a shortcut key.

Class Herwindow extends Frame implements actionlistener{
  MenuBar Menbar;
  Menu menu;
  MenuItem item;
  Menushortcut shortcut = new Menushortcut (keyevent.vk_e);
  ... Item.setshortcut (shortcut);
  ..
}

Select Box menu item

Menus can also contain options that have a persistent selection state, and this special menu can be defined by the JCheckBoxMenuItem class. The JCheckBoxMenuItem object, like a selection box, can indicate whether an option is selected or not, and can be added to the Drop-down menu as a menu item. When you click on the JCheckBoxMenuItem menu, a tick mark or clear tick mark appears on the left side of it. For example, in the class Menuwindow of the example 6.5 program, the code

  AddItem (menu1, "running", this); AddItem (menu1, "skipping", this);


Rewrite the following code to change the two common menu items "running" and "skipping" to two selection boxes menu items:

  JCheckBoxMenuItem item1 = new JCheckBoxMenuItem ("Running");
  jcheckboxmenuitem item2 = new JCheckBoxMenuItem ("skipping");
  Item1.setactioncommand ("Running");
  Item1.addactionlistener (this);
  Menu1.add (item1);
  Item2.setactioncommand ("Skipping Rope");
  Item2.addactionlistener (this);
  Menu1.add (ITEM2);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.