JFrame具有相同的JMenuBar實例

[英]Having JFrame's with the same JMenuBar instance


Like the title suggests, I'd like to have exactly one JMenuBar used in multiple JFrame's. This however doesn't seem to work. Whenever adding the JMenuBar instance to a second JFrame makes the menu disappear from the first JFrame.

如標題所示,我希望在多個JFrame中使用一個JMenuBar。然而,這似乎行不通。每當將JMenuBar實例添加到第二個JFrame時,菜單就會從第一個JFrame中消失。

See my SSCCE:

看到我SSCCE:

public class MenuTest extends JPanel {
    private static final long serialVersionUID = -9209142740183347797L;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });
    }

    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+ SwingUtilities.isEventDispatchThread());

        JMenuBar bar = new JMenuBar();
        bar.add(new JMenu("Test1"));
        bar.add(new JMenu("Test2"));
        bar.add(new JMenu("Test3"));

        JFrame f = new JFrame("Swing Paint Demo 1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MenuTest());
        f.setJMenuBar(bar);
        f.pack();
        f.setVisible(true);


        JFrame f2 = new JFrame("Swing Paint Demo 2");
        f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f2.add(new MenuTest());
        f2.setJMenuBar(bar);
        f2.pack();
        f2.setVisible(true);
    }
}

Might this be possible or is this prohibited?

這是可能的還是禁止的?

1 个解决方案

#1


4  

This can't be done, at least not the way you want to.

這是不可能的,至少不是你想要的方式。

A component may belong to only a single parent container, this means the moment you try applying it to a second container, it will effectively remove it from the previous container.

組件可能只屬於單個父容器,這意味着當您嘗試將其應用到第二個容器時,它將有效地從前一個容器中刪除它。

Instead of trying to maintain a single instance, instead, consider using a "builder" or "factory" pattern which generates new instances of the JMenuBar for you.

與其嘗試維護單個實例,不如考慮使用“構建器”或“工廠”模式,為您生成JMenuBar的新實例。

Too make life easier, I would suggest having a look at How to Use Actions

讓生活更簡單,我建議你看看如何使用行動

Also have a look at The Use of Multiple JFrames, Good/Bad Practice?

也看看多jframe的使用,好/壞的實踐?


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/08/05/730035e6aaee71f493d0a24f34bf8f66.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com