Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The size of a JTextArea

I have a set of JPanel's within a JFrame. One of the panels contains a JTextArea. 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 JTextArea 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 JTextArea 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)

like image 250
Lieuwe Avatar asked Apr 22 '16 13:04

Lieuwe


2 Answers

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:

https://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html

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));
like image 57
Bartvbl Avatar answered Oct 11 '22 08:10

Bartvbl


You have to use layout manager, for start see oficial Oracle docu about layout managers. For your situation, BorderLayout or GridBagLayout should work fine.

Start with:

panel1.setLayout(new BorderLayout());

or

panel1.setLayout(new GridBagLayout());

With GridBagLayout you can more preciselly do layouting (with BorderLayout you have five areas - no more, no less). With GridBagLayout you can do more complicated layouts.

like image 43
1ac0 Avatar answered Oct 11 '22 08:10

1ac0