Reputation: 114
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
Reputation: 32343
A few things
JPopupMenu
. Use JMenu
..setJMenuBar(mb)
.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:
Upvotes: 4
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