Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Resize width only?

 
Derek Boring
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a JLabel and I want to only resize it's width.

Now before you think I'm retarded, consider this: The JLabel automatically resizes to fit all the text. What I want is to set the width of the JLabel, have it word wrap (with <HTML>text</HTML> ) and then automatically resize to the proper height.

myLabel.setSize(newWidth, myLabel.getHeight)

This code changes the width, but overrides the automatic height resize.

Any ideas of how do this?
 
Brian Cole
Author
Ranch Hand
Posts: 908
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Derek Boring:
I have a JLabel and I want to only resize it's width.

Now before you think I'm retarded, consider this: The JLabel automatically resizes to fit all the text. What I want is to set the width of the JLabel, have it word wrap (with <HTML>text</HTML> ) and then automatically resize to the proper height.


I've been in similar situations, not so much with wrapping JLabels but more with things such as JLists set to VERTICAL_WRAP. But let's be careful with the terminology here.

To say that a JLabel "automatically resizes" is misleading. What it does is automatically adjust its preferred size. It is the container's layout manager that actually sets its size.


myLabel.setSize(newWidth, myLabel.getHeight)

This code changes the width, but overrides the automatic height resize.


If the layout manager is null (which I don't recommend) then this will indeed set the width (and height).

In the usual case where the layout manager isn't null, then calling setSize() usually does nothing. This is because the layout manager will clobber the size you set.

For JLabel, though, it can have an effect because the width you specify can cause the label to change the preferred size it reports to the layout manager (to take HTML text wrapping into account).

Usually you're better of calling setPreferredSize() but you are correct that doing so (under many layout managers) will also fix the height of the label, which you don't want.


Any ideas of how do this?


Since you're using Swing's HTML support to get the text to wrap in the first place, why don't you go ahead and really use HTML? You could force the wrapping width with something like:

new JLabel("<html><table><tr><td width='100'>foo bar baz ola qux corge grault garply</td></tr></table></html>")
[ December 28, 2007: Message edited by: Brian Cole ]
 
Derek Boring
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a ton! That is way better than the way I was trying to do it before. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic