tags:

views:

69

answers:

4

Right now I'm trying to use a GridLayout with only a single column. However I'm having a problem where I don't want the object, in this case a JButton, to be stretched the entire width of the JPanel that it's on. Is there a way to decrease the width of the JButton so that it does not stretch the entire width of the JPanel. I've tried using setPreferredSize and setSize with no results.

Is this just the way GridLayout works or is there something I'm missing?

A: 

You could try:

button.setMaximumSize( button.getPreferredSize() );

I think it will be anchored to the left. Otherwise, try putting the button in another panel with a different layout that keeps the button at its preferred size (like FlowLayout), and then put that panel in the grid layout panel.

staticman
+2  A: 

A simple non-elegant solution to this is to embed the JButton in a JPanel, and then insert the JPanel into your layout.

Mark E
A: 

BoxLayout seems to work well in this context. See Specifying Component Sizes, in particular.

trashgod
A: 

GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns.

So that is why the button stretches the entire width of the layout panel it's on. See if any of these links help:

How To Use GridLayout

A Visual Guide to Layout Managers

Miguel Sevilla