dullerthandull
dullerthandull

Reputation: 5

Menu Bar GUI Application

My menuBar isn't showing. Do I need the JPanel for it to show in my GUI?

private void buildCtrlPanel() {
        ctrlPanel = new JPanel();
        menuBar = new JMenuBar();
        fileMenu = new JMenu("File");
        optionsMenu = new JMenu("Options");

        JFrame frame = new JFrame();
        frame.setJMenuBar(menuBar);
        frame.setSize(350, 250);
        frame.setVisible(true);

        ctrlPanel.setLayout(new FlowLayout());
        ctrlPanel.add(menuBar);
        ctrlPanel.add(frame);
        menuBar.add(fileMenu);
        menuBar.add(optionsMenu);
    }

Upvotes: 0

Views: 417

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

You can only add a component to one container. You've added the JMenuBar appropriately to the JFrame -- fine, but then you also add it incorrectly to a JPanel (why?) one that uses a FlowLayout, layouts that don't work well with JMenuBars (again why?). Solution: don't do that. Add it to the JFrame as you're already doing, and leave it be.

You also seem to be adding a JFrame to a JPanel -- something that you shouldn't be doing, and again which suggests that you will want to go through the Swing tutorials before proceding further.

  • You can find links to the Swing tutorials and to other Swing resources here: Swing Info
  • The Swing menu tutorial can be found here: How to use Menus

Upvotes: 1

Related Questions