tags:

views:

993

answers:

5

Is there a way of preserving the natural size of a JButton in the center of a BorderLayout? Right now, it expands in all directions to fill it up, but I want it normal size.

If it isn't possible, how can I get a button to be in the center of a panel with its normal size?

+6  A: 

The component in the center of a BorderLayout is always stretched, you can get round this by adding the button to a JPanel with a FlowLayout and then adding that into the CENTER.

JPanel borderPanel = new JPanel(new BorderLayout());
JButton theButton = new JButton("Click Me");
JPanel flowPanel = new JPanel(new FlowLayout());
flowPanel.add(theButton);
borderPanel.add(BorderLayout.CENTER, flowPanel);
Tom
I think mixing layout is a bad habit as it makes the code confusing
willcodejavaforfood
I disagree - http://madbean.com/anim/totallygridbag/ - I would prefer MigLayout, followed by nested layout, with GridBagLayout last - only if forced to use it.
Nate
A: 

no matter what component you put in the center of a BorderLayout panel, it'll resize vertically and horizontally to fill all the available area. that's the characteristic of the center position.

cd1
A: 

I think you can't do that with BorderLayout. The container's constraints will take priority over preferred sizes.

For manual coding I recommend to have a look at MiG Layout.

kgiannakakis
+1  A: 

I suggest going straight for GridBagLayout. Although it has some odd behaviour and a bad interface, it's a standard layout that does pretty much everything. You are going to need it, so you might as well consistently use the same layout manager even when it is not strictly necessary.

Tom Hawtin - tackline
It is the most powerful one and the only one I use
willcodejavaforfood
A: 

Using a GridBagLayout for such a simple layouts are overkill. I would avoid GridBagLayout as much as possible - use a nested JPanel or MigLayout if you can (external jar)

Keilly