0

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?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Mukhi
  • 143
  • 12
  • The accepted answer will not work well with multi-line text. An easy alternative it to use HTML formatting in a `JLabel` with CSS specifying the target width. The height will be set automatically. Here is [an example](http://stackoverflow.com/a/11034542/418556). – Andrew Thompson Jun 16 '12 at 07:15

1 Answers1

1

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.

npe
  • 15,395
  • 1
  • 56
  • 55