A common technique for multi-line labels is to use a JTextArea.
The Rowan project contains a method that looks like this, which is pretty much identical to code I've written in the past and code I believe I've seen in JGoodies examples as well:
The choice of whether to leave it focusable may depend on context. I usually prefer to allow focus so users can copy the text, but sometimes that will confuse people navigating in dialog boxes who wonder where the cursor went (focusable but non-editable JTextAreas don't display a cursor, at least in Windows look and feels, but it actually still exists).
You might want to steal features from either one to craft the perfect funciton for your needs.
One bit of caution if you use word wrap: I've noticed that JTextArea's with word wrap on are very greedy about space if you don't put them inside a scroll pane. If you allow them to grow by enlarging the window, they refuse to shrink back to their original size if you make the window smaller again! The easy workaround is to put them in a scroll pane and disable scrolling.
Those are excellent ideas David. I never thought of that before.
The easy workaround is to put them in a scroll pane and disable scrolling.
Wouldn't you still see the scroll bars though? This would make it look like a JTextArea and not a Label anymore it would seem.
Joined: Jul 27, 2001
DW: The easy workaround is to put them in a scroll pane and disable scrolling.
GB: Wouldn't you still see the scroll bars though? This would make it look like a JTextArea and not a Label anymore it would seem.
VERTICAL_SCROLLBAR_NEVER and HORIZONTAL_SCROLLBAR_NEVER prevent scroll bars from being displayed at all, and once the text area figures out its preferred size it won't change its mind. This resizing issue was something I randomly encountered once, and it might have been related to my particular choice of layout manager and layout constraints. So consider it noted for future reference: If your JTextAreas are greedy about space, scroll panes may help.