Konstantin
Konstantin

Reputation: 3055

Set a JButton's width to accommodate a certain number of characters

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?

Upvotes: 2

Views: 593

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347294

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...

You Could...

Create a second temporary button with three characters and use it's preferred size as the preferred size of button to b displayed...

You Could...

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

Upvotes: 3

forgivenson
forgivenson

Reputation: 4435

You can use FontMetrics to find the width of a given string with a given font/size.

Pseudo code:

FontMetrics metrics = new FontMetrics(new Font(/*font params here*/));
int width = metrics.stringWidth("My text");
int height = metrics.getHeight();

Then you can set the size of the button accordingly.

Upvotes: 0

Related Questions