Question

So I was trying to google how to set a default size to JButtons so that they don't grow as the JFrame is resized. I didn't see a setDefaultSize method but the closest one I could find that does a similar job is setMaximumSize(). However, it doesn't seem to work in my situation and I'm guessing it's because I'm using Grid Layout for positioning my buttons in the frame, here's a small piece of my code:

rightPanel.add(ButtonA);
rightPanel.add(ButtonB);
rightPanel.add(ButtonC);

outerPanel.add(leftPanel);
outerPanel.add(rightPanel);
getContentPane().add(outerPanel);

Here's a picture of what happens:

enter image description here

I would also like to have my buttons in the middle of the right panel when I'm resizing (just like they are now but a lot smaller). Any idea of how I can fix this? I'm assuming that I have to use another layout or something.

Thanks

EDIT: I modified my code to use BoxLayout but it does not seem to put the buttons in the middle. The X Alignment is working but Y Alignment is not doing anything:

ButtonA.setAlignmentX(CENTER_ALIGNMENT);
ButtonA.setAlignmentY(CENTER_ALIGNMENT);

ButtonB.setAlignmentX(CENTER_ALIGNMENT);
ButtonB.setAlignmentY(CENTER_ALIGNMENT);

ButtonC.setAlignmentX(CENTER_ALIGNMENT);
ButtonC.setAlignmentY(CENTER_ALIGNMENT);

JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

rightPanel.add(ButtonA);
rightPanel.add(ButtonB);
rightPanel.add(ButtonC);

outerPanel.add(leftPanel);
outerPanel.add(rightPanel);
getContentPane().add(outerPanel);

enter image description here

EDIT2: Fixed with vertical glue.

Was it helpful?

Solution

A GridLayout will always resize the components to fill the space available.

Try using a vertical BoxLayoutinstead. See the section from the Swing tutorial on How to Use Box Layout for more information and examples.

OTHER TIPS

Encapsulate each JButton in a JPanel with a FlowLayout, and then add those FlowLayout JPanels to the rightPanel instead of the JButtons themselves. This will allow you to keep your evenly spaced buttons, but won't make them expand to take up the entire space that the parent container has available.

If you don't want them evenly spaced, but to be three consecutive buttons one after another top down, you can make the right panel have a BorderLayout, add a sub panel to the north area of the BorderLayout with the original GridLayout that the right panel had, and then add those FlowLayout panels containing the JButtons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top