I’m relatively new to Java and I’ve spent the past two evenings trying to get my Java program layed out correctly and I’m hoping someone could clear a few things up for me.
The layout was all going well until I decided to add a menu bar to my application using JMenuBar, and now for some reason my application’s menu bar either vanishes, attaches to the top centre of the pane the width of the File menu bar, or works perfectly but hides the buttons below it.
My more recent try has me a little closer, but for some reason the height of the menu bar now seems to be massive when I set the menu bar container to BorderLayout.
Could anyone point me in the right direction as to where I’m going wrong?
JPanel mainPane = new JPanel();
BoxLayout progLayout = new BoxLayout(mainPane, BoxLayout.Y_AXIS);
mainPane.setLayout(progLayout);
setContentPane(mainPane);
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem project = new JMenuItem("New Project");
JMenuItem exit = new JMenuItem("Exit");
file.add(project);
file.add(exit);
JPanel row0 = new JPanel();
BorderLayout menuBarLayout = new BorderLayout();
row0.setLayout(menuBarLayout);
row0.add(menuBar);
add(row0);
JPanel row1 = new JPanel();
row1.setOpaque(false);
row1.add(domainLabel);
row1.add(projectNameInput);
row1.add(userSubmit);
row1.add(userClear);
add(row1);
Many thanks.
*Edit: I finally managed to get it working thanks to the below answer. See comments below to the solution.
To reiterate: Usually I’ve added the JMenuBar to the JFrame itself via its
setJMenuBar(...)method. This will add it in aBorderLayout.NORTHfashion to just above the contentPane. If my JFrame is created elsewhere, I sometimes give classes above a publicgetJMenuBar()method to allow other classes to extract the menu bar created here.If I absolutely need to add the JMenuBar to a JPanel, I give that JPanel a BorderLayout and add the JMenuBar to the
BorderLayout.NORTHposition. If I need other components added via a BoxLayout, then I add a BoxLayout-using JPanel to the main JPanel’sBorderLayout.CENTERposition and add the other sub-components to the BoxLayout-using JPanel.Tutorials include:
Using Top-Level Containers
Using Menus