当文本发生变化时,如何阻止JLabel更改其大小? [英] How do you stop a JLabel changing its size when its text changes?

查看:298
本文介绍了当文本发生变化时,如何阻止JLabel更改其大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中生成一些JComponents并使用GridBag布局来排列它们。我的布局由12行和3列组成,每行包含一个JSlider,一个JCheckBox和一个JLabel。这是我用来生成UI的代码:

I'm generating some JComponents in code and using the GridBag layout to arrange them. My layout consists of 12 rows and 3 columns, with each row consisting of a JSlider, a JCheckBox and a JLabel. Here's the code I'm using to generate the UI:

final int NUM_MOTORS = 12;

// This is the panel I'm adding the components to.
pnlMotorSliders.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();

for (int i = 0; i < NUM_MOTORS; ++i) {
    c.gridy = i;

    // Create the slider
    JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 10, 4085, 10);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.weightx = 0.9;
    pnlMotorSliders.add(slider, c);

    // Create the checkbox
    JCheckBox checkBox = new JCheckBox();
    checkBox.setOpaque(true);
    checkBox.setBackground(Color.blue);
    c.fill = GridBagConstraints.NONE;
    c.gridx = 1;
    c.weightx = 0.1;
    pnlMotorSliders.add(checkBox, c);

    // Create the current label
    JLabel label = new JLabel("0");
    label.setBorder(BorderFactory.createLineBorder(Color.red));
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 2;
    c.weightx = 0.2;
    pnlMotorSliders.add(label, c);
}

我遇到的问题是当我在任何一个文本中设置文本时JLabel,即使我设置的文本宽度远小于JLabel的宽度,它们也会改变宽度并影响布局的其余部分。以下两个屏幕截图展示了我的意思(红色和蓝色边框用于调试目的):

The problem I'm having is that when I set the text in any of the JLabels, they change their width and affect the rest of the layout, even if the width of the text that I'm setting appears to be much smaller than the width of the JLabel. The following two screenshots demonstrate what I mean (the red and blue borders were for debugging purposes):

我已将文本设置为底部JLabel为-12。即使JLabel看起来比文本宽得多,它也改变了它的大小,影响了其余的布局。

I've set the text on the bottom JLabel to "-12". Even though the JLabel appears to be much wider than the text, it has changed its size, affecting the rest of the layout.

为什么会发生这种情况,我该怎么办?防止它?

Why is this happening and what can I do to prevent it?

推荐答案

您可以通过设置最小,首选和最大尺寸来修复标签的大小:

You can fix the size of the labels by setting the minimum, prefered and maximum size:

label.setMinimumSize(width, height);
label.setPreferedSize(width, height);
label.setMaximumSize(width, height);

同时确保将GridBagConstraints#fill设置为NONE,尽管我不确定是否仍然必要的(我认为是)。

Also make sure to set the GridBagConstraints#fill to NONE, although I am not sure if that is still neccessary (I think it is).

编辑:顺便说一下,为了摆脱焦点组件周围那些令人讨厌的虚线,你可以将它设置为不可聚焦:

btw, to get rid of those nasty dashed lines around the focused Component, you can just set it to be not focusable:

slider.setFocusable(false);

这篇关于当文本发生变化时,如何阻止JLabel更改其大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆