【发布时间】:2013-05-08 07:47:26
【问题描述】:
我在使用 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 后,所有MenuItems 都是空的,但存在且功能(ActionExit)也正常工作。使用以下代码 menuFile.add(new JMenuItem("Exit")); 设置新的 JMenuItem 可以正常工作,并且 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);
}
}
【问题讨论】:
-
您实际上没有在菜单中添加任何内容(除了退出)??
-
这只是一个例子。所有菜单都有三个以上的条目。
-
那么,你是如何填充菜单的呢?
-
与“menuItemExit”相同,然后将其添加到菜单中,然后将其添加到JMenuBar。 JMenuItems 都存在并且功能正常工作,但项目上没有文本。
-
我们能看到
ActionExit或任何其他Action类的代码吗?
标签: java swing jframe jmenuitem jmenubar