Skip to main content

Number of lines in a JTextArea when word wrap is on

4 replies [Last post]
Joined: 2004-02-02

I'm using a JTextArea to render cells in a JList. The cells hold a title and a blurb of text, which can be anywhere from zero to about 4 lines long. The blurbs are in the JTextArea with word wrap set on.

Where I'm having problems is that I want the height of the JTextArea to adjust to the length of the wrapped text, which isn't happening. What I see is that each blurb is cut off at one line. I can setRows(3), for example and make every blurb 3 lines, but that's ugly and wastes screen-space.

If I could ask the JTextArea or its underlying document how many lines it's supposed to be **after wrapping** then I could call setRows(n) to the right n in the getListCellRendererComponent() method of my ListCellRenderer.

I always get 1 from getLineCount(), which I take to mean there are no line breaks in the text.

It would be even more fun if I could call a method like this:

Thanks for any hints that save me from pulling my hair out!


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-05-05

If you know the width of the text component, then its easy to find out how many lines of wrapped text it will require.

This is done by the following algorithm:

1) Call textComponent.setSize(width, 9999999);
Here we force it to become the actual width and use an unlimited height.

2) Call textComponent.getPreferredSize();
The preferred "height" it returns is the height it will need *after* line wrapping occurs. To find the number of wrapped lines, just divide the preferred height / line height.

That algorithm is pretty common in the impl. of write line-wrapping text renderers.

Joined: 2004-02-02

Thanks for the reply. I've got a partially working solution based on the technique you mention. So far it's hacked using a predefined size for the enclosing list, which isn't ideal, but works OK in practise. Worse is that it doesn't respond quite right to resizes and the appearence and disappearence of scrollbars.

Since I've cross-posted, I may as well include links to a couple related threads here:



Joined: 2004-02-02

I mocked up a little test example so people can see (and run) my code. It's at:


Joined: 2003-07-17

Hi Chris,

Some time ago I had a similar problem in a TableCellRenderer. I wanted a renderer that was able to limit its width and would calculate the needed height when asked for its preferred size. In a first attempt I tried to tackle it with a renderer based on a JEditorPane, but that didn't help me much.

Finally I found a way to accomplish it by extending DefaultTableCellRenderer and overriding getPreferredSize with a hack.

You can find the code at:

If you want to see it in action, go to my download site

The renderer is used in the Resource Bundle Editor.

Hope this helps.