Reputation: 53
Can someone please tell me how I can add my menubar to the borderlayout NORTH.
I have written it this way.
private void makeFrame()
{
frame = new JFrame("Game");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(menubar, BorderLayout.NORTH);
contentPane.add(new JButton("south"), BorderLayout.SOUTH);
contentPane.add(new JButton("center"), BorderLayout.CENTER);
contentPane.add(new JButton("east"), BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
makeMenuBar();
}
public void makeMenuBar(){
JMenuBar menubar = new JMenuBar();
JMenu menu;
JMenuItem item;
JMenu file = new JMenu("File");
menubar.add(file);
item = new JMenuItem("New Game...");
file.add(item);
item = new JMenuItem("Save As...");
file.add(item);
item = new JMenuItem("Quit");
file.add(item);
}
Can anyone tell me how to add this menubar to border north please.
Upvotes: 0
Views: 1696
Reputation: 347332
Generally speaking, you shouldn't, instead, you should use JFrame#setJMenuBar
instead
The problem you are having seems to be the fact that you are either adding the menu bar to the container BEFORE it's initialized or are creating a new instance of JMenuBar
which is never added to the screen
private void makeFrame()
{
frame = new JFrame("Game");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
// ?? Don't know what this initialised to...
contentPane.add(menubar, BorderLayout.NORTH);
//...
makeMenuBar();
}
public void makeMenuBar(){
// A local variable with the same name...??
JMenuBar menubar = new JMenuBar();
Oh, and the instance you are creating in makeMenuBar
is only local to the method...so it will never have an effect on the menubar
variable you are using in makeFrame
...
Upvotes: 2