Corbin Corbin - 7 months ago 13
Java Question

Make buttons split JPanel - Java Swing

I've got a

BorderLayout
going on, and am working on the North panel. Inside the North panel, I'd like to have 3 components: a picture that is on the left, and two buttons that split the remaining width of the
Frame
. Right now I'm attempting to accomplish this with another
BorderLayout
.

The
Frame
is resizable.

The picture is assigned to
BorderLayout.WEST
, and with the following code I attempt to add another panel that contains only buttons. The panel is then added to the
CENTER
of the
Frame
's
NORTH
layout component.

//create panel to hold buttons
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new BorderLayout());

JButton btnMatrix = new JButton("Matrix View");
btnPanel.add(btnMatrix);
JButton btnList = new JButton("List View");
btnPanel.add(btnList);
add(btnPanel);


however, the buttons both try to take up the entire panel. If I leave it to a flow layout (I don't use
btnPanel.setLayout(new BorderLayout());
in the above code), the buttons sit nicely in the center, but do not expand and share the
btnPanel
.

Thoughts? I'm new enough to Java that I could be going about this the wrong way from the start.

Answer
btnPanel.setLayout(new BorderLayout());

You didn't specify a constraint when you added the buttons to the panel. So both buttons are added to the CENTER. However, only one component can be added to the CENTER, so only the last one added is displayed.

You can try a different layout:

btnPanel.setLayout( new GridLayout(0, 2));

Then each button will be the same size and both buttons will fill the space available.