Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel into GridBagLayout. How to fix the width?

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();

    }

}
like image 506
AgostinoX Avatar asked Jan 18 '23 06:01

AgostinoX


2 Answers

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.

like image 174
Nate W. Avatar answered Jan 20 '23 20:01

Nate W.


Maybe try to use prefered and maximum sizes for JLabel ?

like image 34
Sergii Zagriichuk Avatar answered Jan 20 '23 20:01

Sergii Zagriichuk