views:

529

answers:

2

I'm using a JTextArea to display a long text

JTextArea _definition = new JTextArea(5, 50);

with word-wrap

_definition.setLineWrap(true);
_definition.setWrapStyleWord(true);

embedded in a JScrollPane

add(new JScrollPane(_definition), gbc);

All that is part of a JPanel with the GridBagLayout.

Everything is working fine with shorter text, but when I add a long text with line wraps and the scrollbar is required, pack() goes south and all components have just a minimum size and the dialog is unusable (it's not only the TextArea that is affected).

I've tried to figure out what is going on, but all I could figure out is that is has to do with the text in the TextArea. I'm stuck .. any ideas? Thanks!

+2  A: 

Try calling pack() twice. JTextArea has some odd behavior as described in this entry in the Java bug database. It reports its preferred size initially as a single-line entry that is very wide (e.g. one row, a thousand columns). Once it realizes that it is a certain width, it will then report a correct preferred size for the number of rows it needs.

I've had to do a number of different things to get around this behavior, including subclassing JTextArea and modifying its behavior to be a little smarter. Double pack() may work for you in this case, or you may have to resort to more complicated tweaking depending on how everything in your layout fits together.

Ross
Double pack()-ing didn't work for me .. can you elaborate on "more complicated tweaking" .. thanks!
IronGoofy
A first step is probably to try subclassing JTextArea and track every time the get*Size() methods are called, and see if the results are what you expect them to be.
Ross
A: 

Got it to work .. Ross's answer was giving me some better terms to search for, so thanks for helping me by pointing in the right direction!

 pack();
 _definition.setSize(_definition.getPreferredSize());
 pack();

So double-packing plus some extra ... strange behavior.

IronGoofy
Cool, I'm glad you got it to work. :)
Ross