简体   繁体   English

一个JMenuBar和多个JPanels

[英]One JMenuBar and multiple JPanels

I have a problem with my application GUI. 我的应用程序GUI有问题。 I would like to create one global JMenuBar and share it to other JPanels, but if i want to assign to multi JPanels i have error: 我想创建一个全局JMenuBar并将其共享给其他JPanels,但是如果我想分配给多个JPanels,则会出错:

#

"The menuBar component is added to a parent component more than once. “ menuBar组件已多次添加到父组件。

•panelAll.add(menuBar); •panelAll.add(菜单栏);

•panelTask.add(menuBar);" •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);
}
}

Image 图片

i don't think its a good idea to add a JMenuBar into a JPanel, but if you insist... 我认为将JMenuBar添加到JPanel中不是一个好主意,但是如果您坚持要...

a JMenuBar can be added only to one container, so you need to create more instances of the JMenuBar. JMenuBar只能添加到一个容器,因此您需要创建JMenuBar的更多实例 That should work without problems if you use the 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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM