Corbin Corbin - 2 years ago 156
Java Question

Make buttons split JPanel - Java Swing

I've got a

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
. Right now I'm attempting to accomplish this with another

is resizable.

The picture is assigned to
, and with the following code I attempt to add another panel that contains only buttons. The panel is then added to the
of the
layout component.

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

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

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

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

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download