Posts Tagged ‘wrap’

Wrapping text in a JLabel

Sunday, March 29th, 2009

The Java Swing framework does not seem to supply a component designed to display static text in fluid manner. JLabels are great for displaying a line of text, or a carefully constructed multi-line statement (with suitable line breaks), but provide no support for wrapping. JTextAreas can probably be customized to the point where they appear to look like static labels, but who has the time?

The WrappableJLabel class is an extension to the regular JLabel that provides support for basic wrapping. When called with the default constructor, the component will expand to fill all available space in its parent container, wrapping if necessary. An optional width argument can be passed in the constructor, which will be used as the preferred width of the component.

Download WrappableJLabel.java or view the JavaDoc.

Example usage

The following brief example creates a WrappableJLabel that will expand to fill the surrounding fixed-sized JDialog:

/* Creates a JDialog with a fixed size and places
   a WrappableJLabel inside. */
 
String text = "Lorem ipsum dolor sit amet, consectetur " +
  "adipiscing elit. Vivamus quis magna. Ut ante ligula, " +
  /* HTML line breaks are allowed */
  "pulvinar sed, egestas in, tempor vel, dui.<br>" +  
  "Cras pellentesque sagittis sem. Maecenas venenatis " +
  "odio nec tellus. Nunc a sapien. Nunc quam turpis, " +
  "malesuada in, pellentesque non, fringilla ut, magna.";
 
JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(WindowConstants.
    DISPOSE_ON_CLOSE);
dialog.setPreferredSize(new Dimension(200, 300));
dialog.setLayout(new BorderLayout());    
 
WrappableJLabel wrapLabel = new WrappableJLabel(text);    
dialog.add(wrapLabel, BorderLayout.PAGE_START);    
dialog.add(new JButton("Test button"), BorderLayout.PAGE_END);
 
dialog.pack();    
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);

Comments, suggestions for improvements and bug reports welcome. Due to levels of spam, you’ll need to register to leave a comment – apologies.