I have a very simple JLabel with a quite long text.
The parent layout is a GridBagLayout.
I want the width of the containing Frame not to exceed a certain value, say 160 pixel.
So I set the text as "html", so as the JLabel is able to wrap the text into multiple lines.
Now I just want to "fix" the JLabel width. But I haven't found a way.
The maximum size of the Jframe, the JLabel is not checked by layout manager, so i don't know if there's a "plain" solution.
The very simple example (just fix imports to run) shows the situation.
public class SSCE extends JFrame {
public static void main(String [] args) {
new SSCE().setVisible(true);
}
public SSCE() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JLabel label = new JLabel("<html>one two three four five six seven eight nine ten eleven twelve thirteen");
add(label, gbc);
gbc.gridy=1;
JLabel label2 = new JLabel("other content");
add(label2, gbc);
pack();
}
}
Try specifying the width in the HTML, like this:
String html =
"<html><body width='150px'>" +
"Some content that will span 150 pixels and then line-wrap as necessary" +
"</body></html>";
new JLabel( html );
Note that I've specified pixels (150px
) in this example, but HTML body width can be specified other ways.
Maybe try to use prefered
and maximum
sizes for JLabel
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With