Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop wordwrapped-JTextArea from resizing to fit large content?

I currently have a wordwrapped-JTextArea as a user input window for a chat program. How do I make it so the JTextArea doesn't resize to automatically fit large text? I have already set the JTextArea to be 2 rows:

user_input = new JTextArea();
user_input.addAncestorListener(new RequestFocusListener());
user_input.setRows(2);
user_input.setLineWrap(true);
user_input.setWrapStyleWord(true);
like image 214
Fran Fitzpatrick Avatar asked Dec 17 '22 20:12

Fran Fitzpatrick


1 Answers

You should put your JTextArea in a JScrollPane. This will keep your row size intact, and would have the added benefit of allowing the user to navigate the input. If you want, you can set the scrollpane to never show. You can still rely on the JTextArea component to calculate the height of the rows and then the preferred height of the component.

The call to setRows that you use to indicate the amount of rows visible on your display is a property that is maintained to work with JScrollPane, as described in the JTextArea JavaDoc:

java.awt.TextArea has two properties rows* and columns that are used to determine the preferred size. JTextArea uses these properties to indicate the preferred size of the viewport when placed inside a JScrollPane to match the functionality provided by java.awt.TextArea. JTextArea has a preferred size of what is needed to display all of the text, so that it functions properly inside of a JScrollPane.

*my emphasis

like image 61
akf Avatar answered Dec 19 '22 08:12

akf