• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sizing JButton  RSS feed

 
Barry Brashear
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you set the size on a JButton so the length is always the same
regardless of the length text it is displaying? For instance if a JButton
is displaying "Arrivals" or "Departures", the length of the button is the
same for both.

Thanks.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is that you can try calling setPreferredSize, however some layout managers ignore this dimension. For example, BorderLayout tries to give the component you add to the north or south its preferred height but sets its width to fit; in the east and west this is reversed and the component is given its preferred width and sets its height to fit; and finally, the center component is made to fit and its preferred size is ignored. As another example, GridBaglayout's behaviour depends on the GridBagConstraint's fill attribute.

A long time ago, I was playing around and thought a practice GUI window would look cool if *all* the buttons thoughout the window had the same width, based on the widest text. I solved this by listening to the buttons' text as a bound property, since I didn't want to hardwire in numbers.
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question I have had for a while too. I would like something like this: the JButton sizes itself for "Departures" (or whichever possible text is the longest) and then tells me what the preferred size is, so I can set the preferred size. And I would also like this to happen before I actually display the JButton to the user. So what's the not-so-short answer?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!