Java Swing - Adding JMenuBar to a Child Panel Container

[Updated: Dec 14, 2017, Created: Dec 14, 2017]

This example shows how to add JMenuBar to a child container panel. We just need to add JRootPane instead of our child container (usually a JPanel). JRootPane supports JMenuBar, GlassPane, LayeredPane etc. We will add our child panel to content pane of the JRootPane.


public class ContainerWithMenuBarExample {
  public static void main(String[] args) {
      JFrame frame = createFrame();
      //child container with menu
      frame.add(createContainerWithMenu(), BorderLayout.EAST);
      frame.add(createLabel("Tool Container", Color.LIGHT_GRAY), BorderLayout.NORTH);
      frame.add(createLabel("left container", Color.CYAN.darker()), BorderLayout.WEST);
      frame.add(createLabel("center container", Color.WHITE), BorderLayout.CENTER);

  private static Component createContainerWithMenu() {
      JRootPane rootPane = new JRootPane();
      rootPane.getContentPane().add(createLabel("Right container", Color.PINK));
      JMenuBar menuBar = new JMenuBar();
      menuBar.add(createMenu("File", "Open", "Close", "New", "Exit"));
      menuBar.add(createMenu("Edit", "Cut", "Copy", "Paste"));
      menuBar.add(createMenu("View", "view 1", "view 2"));
      menuBar.add(createMenu("Help", "help 1", "help 2"));
      return rootPane;

  private static JMenu createMenu(String menuLabel, String... subMenuLabels) {
      JMenu menu = new JMenu(menuLabel);
      for (String subMenuLabel : subMenuLabels) {
          JMenuItem menuItem = new JMenuItem(subMenuLabel);
      return menu;

  private static JLabel createLabel(String text, Color color) {
      JLabel label = new JLabel(text, SwingConstants.CENTER);
      return label;

  private static JFrame createFrame() {
      JFrame frame = new JFrame("Panel with JMenuBar Example");
      frame.setSize(new Dimension(400, 300));
      return frame;


Example Project

Dependencies and Technologies Used :

  • datafactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.3.9

Panel Container with Menu Bar Example Select All Download
  • panel-with-menu-bar
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also