Lieuwe Lieuwe - 1 year ago 115
Java Question

The size of a JTextArea

I have a set of

's within a
. One of the panels contains a
. At the moment I create this like so:

JTextArea = new JTextArea(5, 40);

And this gives me a text area which is 5 rows by (roughly) 40 columns.

Vertically this works as I'd like it to, the area fills the entire height of the parent container - probably because the parent is the only element positioned in that row.

Horizontally the parent width is determined by elements underneath and it is (usually) wider than the
is. So I end up with a text area with large margins on either side. What is worse, when I resize the frame smaller to the point where the text area is exactly the width of the parent container, it suddenly 'flicks' and changes into a text area that is 1 row high and is then the width of the parent.

Excuse the crude drawing below which hopefully illustrates the issue.

enter image description here

In short: How to I create a
that always fills the maximum space available to it? (and if possible with a minimum width after which a scrollbar appears if the user sizes the frame even smaller)

Answer Source

In the parent container of the JTextArea (denoted as Panel 1 in your drawing), call the function:

panel1.setLayout(new BorderLayout());

For reference, see this documentation page:

As you only have a single child in panel1, the BorderLayout layout manager of panel1 will by default stretch the text area to use all available space in the parent container.

You may want to take away the constructor parameters specifying the size of your TextArea. The BorderLayout should take care of sizes for you :)

You can request that Swing respects a certain minimum size for the text area by calling:

textArea.setMinimumSize(new Dimension(minimum_width, minimum_height));