views:

25

answers:

3

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);
+1  A: 

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

Jack
+1  A: 

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.

zigdon
+1  A: 

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

akf