spb1994
spb1994

Reputation: 114

Problems with making Swing JMenuBar appear

So, because this is for a school project, I can't post actual source code for what is going on. Instead, I will try to explain what's going on and use some code snippets.

For the project, a JPanel, contained by a JFrame, holds most of the Components of the overall GUI. I'll have like

JButton b1 = new Button("Option 1");
JButton b2 = new Button("Option 2");
JPanel p = new JPanel();
p.add(b1);
p.add(b2);

Adding this to the JFrame object works just fine, but when I have

JMenuBar mb = new JMenuBar();
JPopupMenu pm = new JPopupMenu("File");
mb.add(pm);
myJFrameObject.add(mb);

the menu bar is nowhere to be seen. Should I have used

myJFrameObject.setJMenuBar(mb);

instead? I remember that not really doing anything either. By the way, I have been using BoxLayout for the frame.

Upvotes: 1

Views: 78

Answers (2)

durron597
durron597

Reputation: 32343

A few things

  1. You don't want to use JPopupMenu. Use JMenu.
  2. You are correct that you want to use .setJMenuBar(mb).
  3. Why are you doing JButton b1 = new Button(); does that even compile? Or is that a typo?

Complete working example based on your code:

import java.awt.EventQueue;

import javax.swing.*;

public class MenuExample {
  private JFrame myJFrameObject;

  public MenuExample() {
    myJFrameObject = new JFrame();

    JButton b1 = new JButton("Option 1");
    JButton b2 = new JButton("Option 2");
    JPanel p = new JPanel();
    p.add(b1);
    p.add(b2);
    myJFrameObject.setContentPane(p);

    JMenuBar mb = new JMenuBar();
    JMenu pm = new JMenu("File");
    mb.add(pm);
    myJFrameObject.setJMenuBar(mb);

    myJFrameObject.pack();
  }

  public void setVisible(boolean visible) {
    myJFrameObject.setVisible(visible);
  }

  public static void main(String... args) {
    final MenuExample example = new MenuExample();

    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        example.setVisible(true);
      }
    });
  }
}

Output:

Screenshot of OP's code

Upvotes: 4

user2640782
user2640782

Reputation: 1084

You can achieve what you want with this:

JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("File"); //Use Menu instead of JPopupMenu
mb.add(menu);
myJFrameObject.setJMenuBar(mb); //yes you should use setJMenuBar(mb);

Upvotes: 4

Related Questions