我已经创建了一个带有Pizza JMenu的JMenuBar。JMenu有3个JRadioButtons和2个JCheckBoxes,当菜单项滚动时出现。问题是,当我点击一个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);
}
检查保持菜单打开,看看它是否做你想要的