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.
Joined: Sep 16, 2005
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.
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?