[Advanced-java] JTextArea resizing

Grant Wood grant at nanode.org
Thu May 8 23:58:49 2003


Hello,

I'm having a frustrating time laying out a component which has a 
JTextArea as a child.  My component implements the ListCellRenderer 
interface, so each time it is used, I have to resize it to handle the 
new input values.  (Below is a simple example of what I'm doing)

I can't get the JTextArea to resize itself properly no matter what 
Layout Manager I use.  I've tried BoxLayout, BorderLayout, TableLayout 
(from Swing Conection).  I don't want to use GridBag, here because I 
shouldn't have to.  No matter what properties I set: 
setPreferredSize(), ...MinSize, ... MaxSize(), etc. it won't resize 
itself properly.

What I want is for the JTextArea to have a fixed width and to grow 
vertically to hold the exact amount of text it contains.  Then, my 
component should have no problem growing to hold the resized JTextArea.

In the past I've just written my own JComponents to get this behavior, 
but in the interest of time, I'd prefer not to write my own text 
component here...   I know JTextArea can resize itself, but how do I 
force it to do so with a fixed width?  This is such a common problem, I 
can't believe that there isn't a simple solution, I just can't see it ( 
O'Reilly's Swing book didn't help either).

Thanks in advance for any help with this.

Grant Wood


public class MyPanel extends JPanel implements ListCellRenderer {
     JLabel title;
     JLabel name;
     JTextArea description;
     WhateverLayoutManager layout;
...
	MyPanel() {
		title = new JLabel();
		name = new JLabel();
		description = new JTextArea();
...
		setLayout(layout);

		add(title);
		add(name);
		add(description);
	}

     	public Component getListCellRendererComponent(JList list,
											Object value,
											int index,
                                                  						 boolean 
isSelected,
											boolean cellHasFocus) {
		title.setText( ((MyData) value).getTitle);
		name.setText( ((MyData) value).getName);
		description.setText( ((MyData) value).getDesc())

		layout.layoutContainer(this);
		return this;
	}