Is there a widget for Swing that behaves like a JLabel, that automatically reflows the text if its dimensions have changed? For example:
Large horizontal space available: +--------------+ | Foo bar baz | +--------------+ Small horizontal space available: +---------+ | Foo bar | | baz | +---------+
I am currently using JEditorPane with setContentType("text/html") and HTML content. This works, but it does not use the System’s default label font for displaying the text. Also, I would rather not put HTML tags into my text – at best, \n characters would be transformed into line breaks and everything else would be displayed as text.
I have made a custom UI delegate for
JLabelto support multiple lines. It will wrap your text to fit the available space and also respect hard line breaks. The wrapped text should reflow when the component size changes. The UI delegate listens for changes to the component’s dimension and recalculates the line breaks automatically.Using the UI delegate is as straight forward as:
Or alternatively use the custom
MultiLineLabelclass that in addition to wrapping text supports vertical and horizontal text alignment.Here’s the project: https://github.com/sasjo/multiline
If you compile and try the demo, it should reflow fine on OS X. If I remember correctly there’s some problem with reflowing upon resizing the frame on Windows. Didn’t look in to it at the time, but it seemed that the resized event never propagated to the label.