Re: Layout labels with variable text length
Hi again,
The phrase "a multiline JLabel with HTML text" seems to contradict "put
the entire string into one line." In my experience, JLabel respects HTML
formatting, subject to the constraints imposed by the containing layout.
In this example, the default FlowLayout keeps multiple lines centered as
the panel is resized.
Thank you, John and Roedy. It seems I have been unclear in my first
posting. Let me illustrate my problem with the example code below. It
creates a JFrame containing a JTextField and a JLabel below it. The text
field is 15 columns wide, which I consider a reasonable choice,
independent of the user's screen, font settings, look & feel etc.
Below the text field I have a label which I would like to be as wide as
the text field. I know how wide the text field is
(field.getPreferredSize().getWidth()), but I cannot
label.setPreferredWidth(width)
simply because no such method exists.
What you see when running this example is a label which breaks lines
where this is explicitly stated in the HTML (<br/>, <p>, etc), but I
cannot make it wrap at a certain x-position. I end up with a line that
can even become larger than my screen.
In the past days, I have been looking into LineBreakMeasurer and
TextLayout, but it seems it doesn't help with HTML, and it also seems to
be too much work for such a common requirement.
I can make the text field and the label have equal width by setting
c.fill=BOTH, but this makes the text field as wide as the label, but I
want it the other way round.
I also tried different layout managers and a JEditorPane, but nothing
seems to help.
Any ideas? Am I doing something wrong?
Thanks again,
Simon
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class LabelTest {
private static final String LONG_TEXT = "<html>Very long text. Very
long text. "+
"Very long text. Very long <em>text</em>. Very long text. Very long "+
"text.<br/>Next line. Next line. Next line. Next line. Next "+
"line.</html>";
public static void main(String[] argv) {
JTextField field = new JTextField(15);
field.setMinimumSize(field.getPreferredSize());
JComponent label = new JLabel(LONG_TEXT);
JFrame d = new JFrame("Label test");
d.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
d.getContentPane().setLayout(gbl);
c.weightx = 1d;
c.weighty = 1d;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.NONE;
gbl.setConstraints(field, c);
d.getContentPane().add(field);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
gbl.setConstraints(label, c);
d.getContentPane().add(label);
d.pack();
d.setVisible(true);
}
}