Tutorial for writing graphical menus in Java

  • 2020-04-01 04:15:38
  • OfStack

There are two types of menus: drop-down menus and pop-up menus. This chapter discusses only drop-down menu programming methods. Unlike JComboBox and JCheckBox, menus are always visible in the interface. What the menu has in common with JComboBox is that only one item can be selected at a time.

Selecting an option from a drop-down or pop-up menu generates an ActionEvent event. The event is sent to the monitor for that option, and the meaning of the event is interpreted by the monitor.
Menu bars, menus, and menu items

Drop-down menus are visually represented by the names that appear on the menu bar, which typically appears at the top of the JFrame. A single menu bar displays the names of multiple drop-down menus. There are two ways to activate a drop-down menu. One is to press the button of the mouse, and keep pressing the state, move the mouse, until the mouse is released to complete the selection, high brightness display menu items are selected. Another way is to click the mouse when the cursor is over the menu name in the menu bar, in which case the menu is expanded and the menu items are highlighted.

A menu bar can hold multiple menus (JMenu), and each menu can have many menu items (jmenuitems). For example, the menu bars in the Eclipse environment have the menus File, Edit, Source, Refactor, and so on, and each menu has many menu items. For example, the File menu has menu items like New, Open File, Close, Close All, and so on.

The way to add a menu to the window is to create a menu object, then create several menu objects, put these menu objects in the menu bar, and then add menu items for each menu object as required.
A menu item in a menu can also be a full menu. Since a menu item can be another full menu, a hierarchical menu structure can be constructed.

1. The menu bar
An instance of the class JMenuBar is the menu bar. For example, the following code creates the menubar menubar object:


  JMenuBar menubar = new JMenuBar();


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


  setJMenuBar(menubar);

Common methods of class JMenuBar are:

Add (JMenu m) : adds menu m to the menu bar. CountJMenus () : gets the number of menu bars in a menu bar. GetJMenu (int p) : gets the menu in the menu bar. Remove (JMenu m) : remove menu m from the menu bar.

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

JMenu() : creates a menu with an empty title. JMenu(String s) : creates a menu titled s. Add (JMenuItem item) : adds the menu option specified by the parameter item to the menu. Add (JMenu menu) : adds the menu specified by the parameter menu to the menu. Implementation in the menu embedded submenu. AddSeparator () : draws a separator 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) : inserts a menu item at the menu location. Remove (int n) : remove the menu item from the menu location n RemoveAll () : removes all menu items from the menu.

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

JMenuItem() : constructs a menu item without a title. JMenuItem(String s) : constructs a menu item with a title. SetEnabled (Boolean b) : sets whether the current item is selectable. IsEnabled () : returns whether the current menu item is selectable 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 for clicking on a menu.

Handle menu events
The menu event source is a mouse click on a menu item. The interface to handle the event is an ActionListener, the interface method to implement is actionPerformed(ActionEvent e), and the method getSource() to get the event source.

Applet [' sikisn] n.a method of implementing a menu bar in a window. There is a button, when the button is in the state of open window, click the button will open a window, the window has a menu bar, there are two menus, and each menu has three menu items. When a menu item is selected, the menu item monitor method displays the selected menu item 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(" sports ");
    addItem(menu1,"  running ",this);
    addItem(menu1,"  Jump rope ",this);
    addItem(menu1," Play a ball game ",this);
    JMenu menu2 = JMenu(" entertainment ");
    addItem(menu2," Sing a song ",this);
    addItem(menu2," dancing ",this);
    addItem(menu2," The 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()+" The 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(true);
        bflg = false;
        button.setLabel(" Close my sports entertainment window ");
      }
      else{
        window.setVisible(false);
        bflg = true;
        button.setLabel(" Open my sports entertainment window ");
      }
    }
  }
}

Embed submenus
A menu is created and multiple menu items are created, one of which is another (with other menu items). For example, change the code in the above program to read:


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


Insert the following code to create item41 and item42 menu items and add them to the item4 menu:


  item41= new MenuItem( "The east is red" );
  item42 = new MenuItem( "Peony" );
  item4.add(item41);
  item4.add(item42);


When you click the menu item4, two menu items will be opened for selection.

6. Add exit items to the menu
Add a new menu item, add monitoring to the menu item, use the System. Exit () method in the corresponding monitoring method, you can realize the exit of the Java runtime environment when you click the menu item. For example, here is the code:


 ... 

item7 = new MenuItem( "Quit" );
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 constructor is MenuShortcut(int key). Where the key can be evaluated from keyevent.vk_a to kenevent.vk_z, or from 'a' to' z'. Menu items use the setShortcut(MenuShortcut k) method to set shortcuts. For example, the following code sets the letter e as the 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 a box menu item

Menus can also contain options with persistent selection state, a special menu that 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 also be added to the drop-down menu as a menu item. When you click on the JCheckBoxMenuItem menu, a checkmark appears on its left or clears the checkmark. For example, in the MenuWindow class of the example 6.5 program, place the code


  addItem(menu1, "Running" ,this);addItem(menu1, "Skip" ,this);


Rewrite the following code to change the two normal menu items "running" and "jumping rope" into two menu items in the selection box:


  JCheckBoxMenuItem item1 = new JCheckBoxMenuItem( "Running" ) ; 
  JCheckBoxMenuItem item2 = new JCheckBoxMenuItem( "Jumping rope" );
  item1.setActionCommand( "Running" );
  item1.addActionListener(this);
  menu1.add(item1);
  item2.setActionCommand( "Jumping rope" );
  item2.addActionListener(this);
  menu1.add(item2);


Related articles: