我在使用 JMenuBar 创建 JFrame 时遇到问题。 我这里有一个 MenuBarBuilder 类:
public class MenuBuilder extends JMenuBar
{
private Model model;
public MenuBuilder(Model model)
{
this.model = model;
buildMenuBar();
}
public void buildMenuBar()
{
JMenu menuFile = new JMenu("File");
JMenu menuEdit = new JMenu("Edit");
JMenu menuHelp = new JMenu("Help");
menuHelp.setMnemonic('H');
menuFile.setMnemonic('F');
menuEdit.setMnemonic('E');
JMenuItem menuItemExit = new JMenuItem("Exit");
menuItemExit.setAccelerator(model.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
menuItemExit.setAction(new ActionExit(model));
menuFile.add(menuItemExit);
add(menuFile);
add(menuEdit);
add(menuHelp);
}
}
并且 JFrame 是在另一个类中创建的:
public MainGUI(boolean loadConfig, String loadConfigDir, Model model)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)
{
GlobalVariables.LOGGING_logger.error("Something went wrong while getting the Look and Feel of current Windows Version for Userinterface", e);
}
try
{
this.model = model;
frameMain = new JFrame("MainFrame");
frameMain.setJMenuBar(new MenuBuilder(model));
frameMain.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frameMain.addWindowListener(this);
frameMain.setMinimumSize(new Dimension(500, 500));
frameMain.pack();
frameMain.setSize(800, 800);
frameMain.setLocationRelativeTo(null);
frameMain.setVisible(true);
}
catch (Exception e)
{
GlobalVariables.LOGGING_logger.error("Error while seeting up the main GUI.", e);
MessagesToUser.errorMessageBothFilesIssue(true);
}
}
显示 JFrame
后,所有菜单项都是空的,但已存在,并且函数 (ActionExit
) 也正常工作。使用以下代码设置新的 JMenuItem
menuFile.add(new JMenuItem("Exit"));
按预期工作,并且 JFrame 具有正确的 JMenuBar
。为什么会出现这种情况???
编辑: 这是刚刚退出程序的 ActionExit 类:
public class ActionExit extends AbstractAction
{
private Model model;
public ActionExit(Model model)
{
this.model = model;
}
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
最佳答案
JMenuItem
(实际上是 AbstractButton
的所有子项)从 Action.NAME
属性派生其显示文本。
尝试一些更像...
public class ActionExit extends AbstractAction
{
private Model model;
public ActionExit(Model model)
{
this.model = model;
putValue(NAME, "Exit");
}
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
此外,Action
类还定义了mnemonic
和accelerator
值。
看看How to use Actions和 Action API了解更多详情
关于java - JFrame 上 JMenuBar 中的空 JMenuItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16435316/