简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM