How can I set up a JButton
so that it's wide enough to accommodate 3 digits, without actually calling setText()
on the button to put in those digits?
In other words, how can I set the button's column count? What would be the call equivalent to textField.setColumns(3)
for a JTextField
?
There's no easy way to achieve this, and generally any solution is going to be a little hackey and violate some normally recommended solitons...
Create a second temporary button with three characters and use it's preferred size as the preferred size of button to b displayed...
Get the font metrics from the button, calculate the height and width of the text you would normally otherwise display, add in the insets and margins and set this value as the preferred size of the button...
FontMetrics fm = button.getFontMetrics(button.getFont());
int width = fm.stringWidth("MMM");
int height = fm.getHeight();
Insets insets = button.getInsets();
Insets margins = button.getMargin();
width += insets.left + insets.right + margins.left + margins.right;
height += insets.top + insets.bottom + margins.top + margins.bottom;
button.setPreferrdSize(new Dimension(width, height));
Personally, if I had to do this, I'd go with the first option :P