Mukhi
Mukhi

Reputation: 143

How can I automatically resize the font in a JTextArea to fill all the space allotted?

I won't know how much text will be given to display, and the JTextAreas size is fixed. I want the font to resize to fit the entire JTextArea, and make sure that there's no text cut off.

How can this be achieved?

Upvotes: 0

Views: 1129

Answers (1)

npe
npe

Reputation: 15699

Use FontMetrics class. It will allow you to obtain a pixel width for a text at given font size.

Example use:

Font font = myTextArea.getFont();
FontMetrics fontMetrics = myTextArea.getFontMetrics(font);

int width = fontMetrics.stringWidth("my awesome string");

Now, what you have to do, is to wrap the code above in a loop, increasing, or decreasing the font size until you get width to be more or less equal to myTextArea.getWidth(). When, you are done, just set the font with myTextArea.setFont(font).

Also note, that myTextArea.getWidth() will return the width of the component including borders, scrollbars etc., not just the area to render text, so you will have to calculate the 'real' width of the rendered area first.

Upvotes: 1

Related Questions