我的JFrame中有一个JMenu和一个JPanel
设置代码:
public Gui(String title) {
super(title);
createGUIComponents();
pack();
this.setBackground(Color.WHITE);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(true);
this.setMinimumSize(new Dimension(180, 100));
this.setSize(new Dimension(800, 600));
this.setVisible(true);
}
private void createGUIComponents() {
Container c = this.getContentPane();
JPanel panel = new SpecialJPanel();
JMenuBar menu = new JMenuBar();
fileMenu = new JMenu("File", false);
fileMenu.add("New");
fileMenu.add("Open");
fileMenu.add("Save");
fileMenu.add("Save As");
c.add(panel, "Center");
c.add(menu, "Center");
}每当我单击JMenuBar上的“文件”菜单按钮时,都没有显示任何内容。我认为它被JPanel屏蔽了,它正在不断更新。有没有办法解决这个问题?
发布于 2013-04-29 09:20:01
您没有将菜单添加到menuBar,因此添加以下行:
menu.add(fileMenu);此外,您应该使用c.add(menu),而不是
setJMenuBar(menu);发布于 2013-04-29 11:12:16
BorderLayout
BorderLayout的标准布局是JFrame提供了5个区域,每个区域可以接受1组件。那么当代码是这样写的时候:
c.add(panel, "Center");
c.add(menu, "Center");它实际上应该读起来更像这样:
c.add(panel, BorderLayout.CENTER); // Don't use magic numbers!
c.add(menu, BorderLayout.PAGE_START);话虽如此,JFrame有一种更好的方式来显示JMenuBar,详见answer by @CoderTitan。
https://stackoverflow.com/questions/16269932
复制相似问题