Fran Fitzpatrick
Fran Fitzpatrick

Reputation: 18502

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);

Upvotes: 5

Views: 9739

Answers (3)

akf
akf

Reputation: 39485

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

Upvotes: 7

zigdon
zigdon

Reputation: 15063

It's a function of the layout manager you're using, but you can try to force it by setting setPreferredSize() and setMaximusSize() on your text area.

See the docs for JComponent.

Upvotes: 2

Jack
Jack

Reputation: 133577

Use setPreferredSize(new Dimension(...)) so that the JTextArea will keep the dimension you set.,

Upvotes: 4

Related Questions