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 ]