18. Java Swing JMenu and JPopupMenu: menus and pop-up menus

The menu is implemented by JMenu class in Swing and can contain multiple menu items and menus with separators.

In the menu, the menu item is represented by JMenuItem class and the separator is represented by JSeparator class.

Menus are essentially buttons with associated JPopupMenu. When the "button" is pressed, JPopupMenu will be displayed.
If the "button" is located on the JMenuBar, the menu is the top-level window.
If button is another menu item, JPopupMenu is the drop-down menu.

Common methods of JMenu class

There are two common construction methods for creating menus: JMenu() and JMenu(String s).
The first construction method creates a JMenu object without text,
The second constructor creates a JMenu object with the specified text. The common methods of JMenu class are shown in Table 1.

Common methods of JMenu class:

  • add(Action a) -- create a new menu item connected to the specified Action object and append it to the end of this menu
  • add(Component c) -- append a component to the end of this menu
  • add(Component c,int index) -- adds the specified component to the given location of this container
  • add(JMenuItem menultem) -- append a menu item to the end of this menu
  • add(String s) -- creates a new menu item with the specified text and appends it to the end of this menu
  • addSeparator() -- append the new separator to the end of the menu
  • doCliclc(int pressTime) -- execute the "click" operation programmatically
  • getDelay() -- return the suggested delay before the submenu pops up or down (in milliseconds)
  • getltem(int pos) -- returns the JMenuItem at the specified location
  • getItemCount() -- returns the number of items on the menu, including the separator
  • getMenuComponent(int n) -- returns the component at position n
  • getMenuComponents() -- returns the Component array of the menu subcomponent
  • getSubElements() -- returns an array consisting of menurelement, which contains the submenus of this menu component
  • insert(JMenuItem mi,int pos) -- inserts the specified JMenuitem at a given location
  • insert(String s,pos) -- inserts a new menu item with specified text at a given position
  • insertSeparator(int index) -- inserts a separator at the specified position
  • isMenuComponent(Component c) -- returns true if the specified component exists in the submenu hierarchy
  • isPopupMenuVisible() -- return rue if the pop-up window of the menu is visible
  • isSelected() returns true if the menu is the currently selected (i.e. highlighted) menu
  • isTopLevelMenu() -- returns true if the menu is the "top-level menu" (that is, the direct child of the menu bar)
  • setDelay(int d) -- set the recommended delay before PopupMenu of the menu pops up or down
  • setMenuLocation(int x,int y) -- sets the location of the pop-up component
  • setPopupMenuVisible(boolean b) -- sets the visibility of the menu pop-up
  • setSelected(boolean b) -- sets the selection status of the menu

Example 1
If the menu is attached to the JMenuBar object, this menu is the menu in the menu bar.

If the menu is attached to the JPopupMenu object, this menu is a pop-up menu.

The principle of realizing menu bar and pop-up menu is the same, but there are some differences in specific implementation methods.

Next, write a case to use JMenuBar class to create a menu window containing "file" menu and "Edit" menu. The main implementation codes are as follows:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public class JMenuDemo1 extends JMenuBar
{
    public JMenuDemo1()
    {
        add(createFileMenu());    //Add file menu
        add(createEditMenu());    //Add edit menu
        setVisible(true);
    }
    public static void main(String[] agrs)
    {
        JFrame frame=new JFrame("menu bar");
        frame.setSize(300,200);
        frame.setJMenuBar(new JMenuDemo1());
        frame.setVisible(true);
    }
    //Define file menu
    private JMenu createFileMenu()
    {
        JMenu menu=new JMenu("file(F)");
        menu.setMnemonic(KeyEvent.VK_F);    //Set quick access character
        JMenuItem item=new JMenuItem("newly build(N)",KeyEvent.VK_N);
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK));
        menu.add(item);
        item=new JMenuItem("open(O)",KeyEvent.VK_O);
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.CTRL_MASK));
        menu.add(item);
        item=new JMenuItem("preservation(S)",KeyEvent.VK_S);
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK));
        menu.add(item);
        menu.addSeparator();
        item=new JMenuItem("sign out(E)",KeyEvent.VK_E);
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,ActionEvent.CTRL_MASK));
        menu.add(item);
        return menu;
    }
    //Define the edit menu
    private JMenu createEditMenu()
    {
        JMenu menu=new JMenu("edit(E)");
        menu.setMnemonic(KeyEvent.VK_E);
        JMenuItem item=new JMenuItem("revoke(U)",KeyEvent.VK_U);
        item.setEnabled(false);
        menu.add(item);
        menu.addSeparator();
        item=new JMenuItem("Clip(T)",KeyEvent.VK_T);
        menu.add(item);
        item=new JMenuItem("copy(C)",KeyEvent.VK_C);
        menu.add(item);
        menu.addSeparator();
        JCheckBoxMenuItem cbMenuItem=new JCheckBoxMenuItem("Auto wrap");
        menu.add(cbMenuItem);
        return menu;
    }
}

The above code calls the setMnemonic() method of JMenu object to set the quick accessor of the current menu.

The symbol must correspond to a key on the keyboard and should use Java awt. event. One of the VK-XXX key codes defined in keyevent is specified.

Tip: quick access character is a shortcut key, which is usually activated when ALT key and a letter are pressed. For example, the commonly used Alt+F is the quick access character of the file menu.

The JMenuItem class implements the menu items in the menu. A menu item is essentially a button in a list. When the user clicks the button, the operation associated with the menu item is performed.

Common construction methods of JMenuItem:

  • JMenuItem(String text): creates a JMenuItem with the specified text.
  • JMenuItem(String text,Icon icon): creates a JMenuItem with the specified text and icon.
  • JMenuItem(String text,int mnemonic): creates a JMenuItem with the specified text and keyboard mnemonic.

In this example, after the menu item is created, the setAccelerator(KeyStroke) method of JMenuItem object is called to set the modification key, which can directly call the operation listener of the menu item without displaying the menu hierarchy. In this example, the event listening mechanism is not implemented, so you will not get any response from the program when using the shortcut key, but the shortcut key will appear in the menu item.

Running the example, figure 1 shows the effect of expanding the "file" menu, and Figure 2 shows the effect of expanding the "Edit" menu.

Pop up menu JPopuMenu

Pop up menu is implemented by JPopupMenu class. It is a small window that can pop up and display a series of options.

It is also used to display the "pull right" menu when the user selects a menu item and activates it, which can be used anywhere else you want the menu to appear. For example, when a user right clicks in a specified area.

Common methods of JPopMenu class:

  • getInvoker() -- returns the component that is the "caller" of this pop-up menu
  • setInvoker(Component invoker) -- set the caller of the pop-up menu, that is, the component in which the pop-up menu is displayed
  • addPopupMenuListener(PopupMenuListener1) -- add PopupMenu listener
  • removePopupMenuListener(PopupMenuListener1) -- removes the PopupMenu listener
  • getPopupMenuListeners() -- returns an array of all popupmenulisteners added to this JMenuitem using addPopupMenuListener()
  • getLabel() -- returns the label of the pop-up menu
  • setLabel(String label) -- sets the label of the pop-up menu
  • show(Component invoker,int x,int y) -- displays pop-up menus at positions X and Y in the coordinate space of the caller
  • getComponentIndex(Component c) -- returns the index of the specified component

Example 2
Use the JPopupMenu class to create a pop-up menu and use submenus in the menu. The main implementation codes are as follows:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
public class JPopupMenuDemo extends JFrame
{
    JMenu fileMenu;
    JPopupMenu jPopupMenuOne;//Represents a menu that can pop up dynamically at a specified position in the component
    JMenuItem openFile,closeFile,exit;//The JMenuItem class represents items in a menu
    JRadioButtonMenuItem copyFile,pasteFile;//The JRadioButtonMenuItem class represents a check box that can be included in a menu
    ButtonGroup buttonGroupOne;
    public JPopupMenuDemo()
    {
        jPopupMenuOne=new JPopupMenu();    //Create a jPopupMenuOne object
        buttonGroupOne=new ButtonGroup();
        //Create a file menu and submenus, and add submenus to the file menu
        fileMenu=new JMenu("file");
        openFile=new JMenuItem("open");
        closeFile=new JMenuItem("close");
        fileMenu.add(openFile);
        fileMenu.add(closeFile);
        //Add fileMenu menu to pop-up menu
        jPopupMenuOne.add(fileMenu);
        //Add delimiter
        jPopupMenuOne.addSeparator();
        //Create a radio menu item and add it to the ButtonGroup object
        copyFile=new JRadioButtonMenuItem("copy");
        pasteFile=new JRadioButtonMenuItem("paste");
        buttonGroupOne.add(copyFile);
        buttonGroupOne.add(pasteFile);
        //Add copyFile to jPopupMenuOne
        jPopupMenuOne.add(copyFile);
        //Add pasteFile to jPopupMenuOne
        jPopupMenuOne.add(pasteFile);
        jPopupMenuOne.addSeparator();
        exit=new JMenuItem("sign out");
        //Add exit to jpopupmuanone
        jPopupMenuOne.add(exit);
        //Create listener object
        MouseListener popupListener=new PopupListener(jPopupMenuOne);
        //Register listener with main window
        this.addMouseListener(popupListener);
        this.setTitle("Pop up menu");
        this.setBounds(100,100,250,150);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String args[])
    {
        new JPopupMenuDemo();
    }
    //Add an internal class that extends the MouseAdapter class to handle mouse events
    class PopupListener extends MouseAdapter
    {
        JPopupMenu popupMenu;
        PopupListener(JPopupMenu popupMenu)
        {
            this.popupMenu=popupMenu;
        }
        public void mousePressed(MouseEvent e)
        {
            showPopupMenu(e);
        }
        public void mouseReleased(MouseEvent e)
        {
            showPopupMenu(e);
        }
        private void showPopupMenu(MouseEvent e)
        {
            if(e.isPopupTrigger())
            {
                //If the current event is related to a mouse event, a menu pops up
                popupMenu.show(e.getComponent(),e.getX(),e.getY());
            }
        }
    }
}

When using the pop-up menu, you must pay attention to the hierarchical relationship and the position of the menu. After the program runs, because the menu is not activated, the window is blank, as shown in Figure 1. Right click to view the pop-up menu, as shown in Figure 2.

Posted by KMC1499 on Mon, 09 May 2022 21:35:30 +0300