How to Line Wrap JLabel (Java Swing)

Leave a comment

July 17, 2012 by huionn

I think line wrapping JLabel is a common requirement for Java Swing application. There are at least 4 ways to achieve it, with their own limitation.

  1. JLabel with <html> tag: <br> will break the line. Alternatively, css style “width:100px” or attribute “WIDTH=100” (capital and no quote) can be used to limit the width.
    <html><div style=\"width:100px;\">This is a very long text.</div><html>
    <html><div WIDTH=100>This is a very long text.</div><html>

    source: http://stackoverflow.com/questions/2420742/make-a-jlabel-wrap-its-text-by-setting-a-max-width

  2. Use JTextArea and change its style to mimic JLabel: background color, font, and non-editable.
  3. Use JXLabel from SwingX and set its multiLine to true (JXLabel.setLineWrap(true)).
  4. Use MultiLineLabelUI as shown in http://samuelsjoberg.com/archive/2009/10/multiline-labels-in-swing (however MultiLineLabelUI has a issue with its width calculation. It makes assumption that the width of label is (parent container width – insets).)

However the tricky part is to implement auto-resize when the container size changes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: