Stijn Vanpoucke
Stijn Vanpoucke

Reputation: 1425

How do I set the font size of the text on a swing jButton to the maximum size who fits the jButton

I've got a jPanel with a jButton, and the user can define the size of the jPanel when launching the application using parameters, the jButton sizes according to the jPanel.

The problem is when I use a fixed font and the Panel is large, then the font looks very small, and vica versa.

So the font size should always be the maximum font size who fits in the button.

Upvotes: 1

Views: 1628

Answers (2)

Puce
Puce

Reputation: 38152

Not sure, but you might find the size using the Graphics.getFontMetrics() method inside the paintComponent-method? Maybe you can use the FontMetrics.getStringBounds() methods and test if the button contains that rectangle (RectangularShape.contains()).

You could use a binary search algorithm to find the max font.

Make sure you take the insets into account.

Upvotes: 3

jzd
jzd

Reputation: 23639

Rather than messing with different font sizes. I would suggest playing with the layout and keep the button from growing with the Panel size. Allow the extra space to be taken up by other components in your panel.

Upvotes: 1

Related Questions