如何将JMenuBar添加到JTabbedPane?

时间:2016-11-27 10:55:12

标签: java swing user-interface jtabbedpane jmenubar

我需要创建JMenuBar,该JTabbedPane将显示在名为shapes的{​​{1}}下。当我更改选项卡时,菜单栏将不会显示在其他选项卡中。你可以从图像中看出我的意思。

我创建了一个菜单栏并将其添加到JFrame,但这不是我的意思。如果你不明白一点,请让我解释一下。

public class Gui extends JPanel {

    JFrame frame;
    JTabbedPane tabbedPane;
    JMenuBar menuBar;
    JMenu createShapes, display, help;
    JMenuItem RandomShapes, Rectangle, Circle, Square;

    public void createFrame() {
        frame = new JFrame();
        frame.setSize(1000, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setVisible(true);
        frame.setFocusable(false);
        setVisible(true);
        setSize(1000, 600);
    }

    public void createMenus() {
        menuBar = new JMenuBar();

        //frame.setJMenuBar(menuBar);

        createShapes = new JMenu("CreateShapes");
        menuBar.add(createShapes);
        display = new JMenu("Display");
        menuBar.add(display);
        help = new JMenu("Help");
        menuBar.add(help);

        RandomShapes = new JMenuItem("Random Shapes");
        createShapes.add(RandomShapes);
        Rectangle = new JMenuItem("Rectangle");
        createShapes.add(Rectangle);
        Circle = new JMenuItem("Circle");
        createShapes.add(Circle);
        Square = new JMenuItem("Square");
        createShapes.add(Square);

    }


    public Gui() {

        createFrame();
        createMenus();

        frame.add(this);

            //===frames part
        tabbedPane = new JTabbedPane();
        frame.getContentPane().add(tabbedPane);

        JPanel gui2 = new JPanel();

        tabbedPane.addTab("Shapes", this);
        tabbedPane.addTab("Images", gui2);
            //===endframespart

    }


}

其他标签图片

The other tab image

形状选项卡图像

Shapes tab image

1 个答案:

答案 0 :(得分:1)

实际上,您无法将菜单栏设置为JTabbedPane。 您需要在JTabbedPane的其中一个选项卡中添加JInternalFrame 你可以调用JInternalFrame的setJMenuBar。

这是一个简单的例子:

JInternalFrame jInternalFrame = new JInternalFrame();
jMenuBar = new javax.swing.JMenuBar();
jMenu1 = new JMenu("Save");
jMenu2 = new JMenu("Open");
jMenuBar.add(jMenu1);
jMenuBar.add(jMenu2);
jInternalFrame.setJMenuBar(jMenuBar);
tabbedPane.addTab("tab3", jInternalFrame);