如何在GridBagLayout中将JLabel的宽度固定?

4

我有一个非常简单的JLabel,其文本内容相当长。
父布局是GridBagLayout。
我希望容器框架的宽度不超过一定值,比如160像素。
所以我将文本设为“html”,以便JLabel能够将文本换行成多行。
现在我想要“固定”JLabel的宽度。 但是我还没有找到方法。
由于布局管理器不检查JFrame和JLabel的最大大小,因此我不知道是否存在“普通”的解决方案。

以下是代码示例:

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

    }

}
3个回答

5

尝试在HTML中指定宽度,例如:

String html = 
    "<html><body width='150px'>" +
    "Some content that will span 150 pixels and then line-wrap as necessary" +
    "</body></html>";
new JLabel( html );

请注意,此示例中我指定了像素(150px),但HTML body宽度还可以通过其他方式指定。

1
@AndrewThompson:什么?那只是一个任意的数字,重点是你可以用这种方式指定宽度。事实上,你就是在这里向我展示的 :) - Nate W.
@AndrewThompson: 哈哈:D。我看到了你的编辑,我不知道像素是默认设置。我愿意打赌相对大小(150%)在这里不起作用,因为没有父HTML组件,对吧? - Nate W.
“..对吧?” 你的JRE和我的一样好。你尝试过了吗? - Andrew Thompson

2
也许尝试使用preferedmaximum大小来设置JLabel

label.setMaximumSize(new Dimension(80,Integer.MAX_VALUE)); 当然也尝试过了,但并没有起作用。在javadoc中,GridBagLayout被称为会考虑最大值。也许在其他情况下它会评估最大值,比如在重新分配额外空间时……我不知道。对于我来说理解这个布局管理器的所有细节还是相当复杂的。 - AgostinoX
我认为最大值和首选大小应该等于您的最大值,对于您来说是160。 - Sergii Zagriichuk

2

有一个类似的问题:"通过设置最大宽度使JLabel换行"

这个回答似乎是正确的:JLabel最大宽度答案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接