Halil Eren Ertan Halil Eren Ertan - 13 days ago 8
Java Question

How to add a JMenuBar to a JTabbedPane?

I need to create a

JMenuBar
that will be shown under of
JTabbedPane
named as
shapes
. When I changed tab, menu bar will not be shown in the other tab. You can see what I mean from images.

I created a menu bar and add it to
JFrame
but that is not I mean. If you did not understand a point let me explain.

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();
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



The other tab image

Shapes tab image



Shapes tab image

Answer

Actually, you cannot set menu bar to JTabbedPane. You need to add JInternalFrame inside one of the tabs of JTabbedPane, then you can call setJMenuBar of JInternalFrame.

Here is a simple example:

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