我的应用程序GUI出现问题。我想创建一个全局JMenuBar并将其分享给其他JPanels,但如果我想分配给多个JPanels我有错误:
" menuBar组件不止一次添加到父组件。
•panelAll.add(菜单栏);
•panelTask.add(菜单栏);"
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
JPanel panelAll = new JPanel();
frame.getContentPane().add(panelAll, "name_218556506364138");
panelAll.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 795, 21);
panelAll.add(menuBar);
JPanel panelTask = new JPanel();
frame.getContentPane().add(panelTask, "name_218567310779840");
panelTask.setLayout(null);
panelTask.add(menuBar);
JPanel panelMyTask = new JPanel();
frame.getContentPane().add(panelMyTask, "name_218578712986622");
panelMyTask.add(menuBar);
JPanel panelMySoftware = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_218590026900741");
panelMySoftware.add(menuBar);
JPanel panelMyDevices = new JPanel();
frame.getContentPane().add(panelMyDevices, "name_218598029981563");
panelMyDevices.add(menuBar);
}
}
答案 0 :(得分:1)
我不认为将JMenuBar添加到JPanel中是一个好主意,但如果你坚持......
JMenuBar只能添加到一个容器中,因此您需要创建更多JMenuBar的实例。如果您使用command pattern,那应该没有问题。
//first instance
JMenuBar taskMenuBar = new MyJMenuBarImplementation();
JPanel panelMyTask = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_xxx");
panelMyTask.add(taskMenuBar);
//second instance
JMenuBar softwareMenuBar = new MyJMenuBarImplementation();
JPanel panelMySoftware = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_yyy");
panelMySoftware.add(softwareMenuBar);
//and so on...