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.
- 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>
- Use JTextArea and change its style to mimic JLabel: background color, font, and non-editable.
- Use JXLabel from SwingX and set its multiLine to true (JXLabel.setLineWrap(true)).
- 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.