我用Pizza JMenu创建了一个JMenuBar。 JMenu有3个JRadioButtons和2个JCheckBox,当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);
}