How do you stop a JLabel changing its size when its text changes?

Amr Bekhit picture Amr Bekhit · Jun 5, 2012 · Viewed 21.5k times · Source

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

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):

The layout before changing the JLabel text.

The layout after changing the bottom JLabel text. Notice how the label has gotten bigger.

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?

Answer

brimborium picture brimborium · Jun 5, 2012

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

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

EDIT: 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);