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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
FontMetricsclass. It will allow you to obtain a pixel width for a text at given font size.Example use:
Now, what you have to do, is to wrap the code above in a loop, increasing, or decreasing the font size until you get
widthto be more or less equal tomyTextArea.getWidth(). When, you are done, just set the font withmyTextArea.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.