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

I currently have wordwrapped-JTextArea as a user input window for a chat program. How to do this so that JTextArea does not resize to fit automatically into large text? I already installed JTextArea as 2 lines:

user_input = new JTextArea(); user_input.addAncestorListener(new RequestFocusListener()); user_input.setRows(2); user_input.setLineWrap(true); user_input.setWrapStyleWord(true); 
+4
source share
3 answers

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

The setRows call that you use to indicate the number of lines visible on your display is a property that is supported for working with JScrollPane , as described in the JTextArea JavaDoc :

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

* my emphasis

+6
source

Use setPreferredSize(new Dimension(...)) to have JTextArea keep the given size.,

+4
source

This is the layout manager function that you use, but you can try to force it by setting setPreferredSize() and setMaximusSize() in the text area.

See docs for JComponent .

+2
source

All Articles