Reputation: 235
I am creating a GUI for an arcade game. It consist of a single JFrame with some JPanels and one JMenu as shown in the figure:
I've been trying using BorderLayout but it doesn't show the panels properly. What I get is that the JMenu shows properly. [1] adjusts its width to content the buttons inside it. The JPanel [2] fulfill almost the rest of the screen. And [3] shows just as a thin line at the end.
Here's the fragment of code that I use to put them in position:
add(new TopMenu(), BorderLayout.PAGE_START); // JMenu
add(new LeftPanel(), BorderLayout.WEST); // [1]
add(new StatusPanel(), BorderLayout.CENTER); // [2]
add(new GameUI(), BorderLayout.LINE_END); // [3]
Any suggestions of what could be provoking this behavior are welcome.
Upvotes: 1
Views: 86
Reputation: 51485
Your JPanel
's have to have Swing components inside, or else they will shrink to the minimum size when you call pack() on the JFrame
.
Since you're creating a game, you'll need to set the preferred size on your JPanel
's, and set the preferred size on the JFrame
. I'm assuming you'll want to paint at least one of the JPanel
components directly using the paintComponent
method.
You can nest JPanel-2 and JPanel-3 in a rightPanel. You can use FlowLayout
for the rightPanel itself, as well as putting JPanel-1 and rightPanel into the JFrame
.
If you insist on using a layout manager that will lay out the 3 JPanel
's without nesting, you will have to use the GridBagLayout
. JPanel-1 will be 1 column wide and 2 rows deep. JPanel-2 will be 1 column wide and 1 column deep. JPanel-3 will be 1 column wide and 1 column deep.
You'll still have to set the preferred size of the 3 JPanel
's.
Upvotes: 1
Reputation: 285405
You can always nest JPanels/containers, each using its own layout. So the overall layout could be a BorderLayout with the menu at the BorderLayout.NORTH and the JPanel [1] on the BorderLayout.EAST side, then nest a JPanel into the BorderLayout.CENTER position using either another BorderLayout or a BoxLayout and put your other two JPanels into this JPanel. For instance this CENTER JPanel could use BorderLayout and it could hold JPanel [2] in its BorderLayout.NORTH position and JPanel [3] in its BorderLayout.CENTER position.
Upvotes: 3