2

我创建了一个带有 Pizza JMenu 的 JMenuBar。JMenu 有 3 个 JRadioButtons 和 2 个 JCheckBoxes,它们会在 menuItems 滚动时出现。问题是当我单击 JRadioButton 或 JCheckBox 时,整个菜单都会消失。是否有特定的方法或任何其他方式可以阻止这种情况发生?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MenuExamplePizza extends JFrame
{
    private JMenuBar menuBar;
    private JMenu menu, sizeMenu, extrasMenu, helpMenu;
    private JMenuItem menuItem;private JRadioButtonMenuItem smallrbMenuItem, medrbMenuItem, largerbMenuItem;
    private JCheckBoxMenuItem peppchMenuItem, anchMenuItem;

public MenuExamplePizza()                                                               // Default Constructor
{
   menuBar = new JMenuBar();                                                                        //Create the menu bar

    menu = new JMenu("Pizza");                                                                      //Build the first menu
    menu.setMnemonic('P');
    menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    menuItem = new JMenuItem("Total");
    menuItem.setMnemonic('T');
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.CTRL_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
    menu.add(menuItem);
    menu.addSeparator();

    sizeMenu = new JMenu("Size");
    sizeMenu.setMnemonic('S');
    ButtonGroup group = new ButtonGroup();
    smallrbMenuItem = new JRadioButtonMenuItem("Small");
    group.add(smallrbMenuItem);
    sizeMenu.add(smallrbMenuItem);
    medrbMenuItem = new JRadioButtonMenuItem("Medium");
    group.add(medrbMenuItem);
    sizeMenu.add(medrbMenuItem);
    largerbMenuItem = new JRadioButtonMenuItem("Large");
    group.add(largerbMenuItem);
    sizeMenu.add(largerbMenuItem);
    menu.add(sizeMenu);

    extrasMenu = new JMenu("Extras");
    extrasMenu.setMnemonic('E');
    peppchMenuItem = new JCheckBoxMenuItem("Pepperoni");
    extrasMenu.add(peppchMenuItem);
    anchMenuItem = new JCheckBoxMenuItem("Anchovies");
    extrasMenu.add(anchMenuItem);
    menu.add(extrasMenu);

    menu.addSeparator();                                                                        // a group of radio button menu items                                                                       

    menuItem = new JMenuItem("Exit");
    menuItem.setMnemonic('x');
    menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
    menu.add(menuItem);

    helpMenu = new JMenu("Help");                                                           //Build second menu in the menu bar.

    menuBar.add(menu);
    menuBar.add(helpMenu);
    add(menuBar);
    setJMenuBar(menuBar);
}
4

1 回答 1

3

查看保持菜单打开,看看它是否符合您的要求。

于 2013-03-31T20:25:38.720 回答