If you want a multilne label then you simply use HTML
in its text, as they support its use. Therefore, use line brake tag </br>
to break lines or put separate lines in <p></p>
paragraph tags.
Do not forget to mark that you want to use HTML for a JLabel
by starting its text with the <html>
tag.
More available here.
BTW I forgot to check if there were other related questions about JLabel
use and there were at least a few, check this or this. :)
EDIT:
For a working sample, showing a different approach, without setting a style and with use of paragraph and label taking available space, please see below:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
public class LabelHTMLAutoResize {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout());
JLabel l = new JLabel("<html><p> Some verrrry long text Some verrrry long Some verrrry long text dsa ads oiosi o</p>");
l.setVerticalAlignment(SwingConstants.TOP);
l.setOpaque(true);
l.setBackground(Color.green);
p.add(l);
f.setContentPane(p);
/* good practice is to use f.pack(); and let the size be automatically calculated but we want to show line wrapping thus frame size is set */
f.setSize(200, 200);
f.setVisible(true);
}
});
}
}
every x chars – Whimusical Jun 14 '12 at 13:43