1

i want to set the size of a JLabel to a specific (minimum) size via setPreferredSize(). If the text inside the JLabel doesn't fit anymore, the JLabel should grow.

The problem now is:

  • after label.setPreferredSize(new Dimension(50,20));
  • i do setText("new long text"); but the size won't change
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class LabelTest
{
    public static void createWindow()
    {
        JFrame frame = new JFrame();

        JLabel label = new JLabel("Text");
        System.out.println(label.getPreferredSize().width); // 25
        label.setText("New long text");
        System.out.println(label.getPreferredSize().width); // 77 - JLabel grows as expected

        label.setText("Text");
        System.out.println(label.getPreferredSize().width); // 25
        label.setPreferredSize(new Dimension(50, 20));
        System.out.println(label.getPreferredSize().width); // 50 - JLabel grows to given size as expected
        label.setText("New long text");
        System.out.println(label.getPreferredSize().width); // 50 - it should be 77 again

        frame.add(label);
        frame.setPreferredSize(new Dimension(200, 100));
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createWindow();
            }
        });
    }
}

So i need a solution to get the new preferred size when a text is set after i already set the preferred size manually.

If you need more information just ask.

Thanks in advance!

Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34
Nikolai
  • 25
  • 1
  • 5
  • So in fact, you would like something like the possibility to override getMinimumSize()... Hmmm. – JB Nizet Nov 11 '13 at 13:28
  • 3
    unrelated: [don't use setXXSize, ever](http://stackoverflow.com/a/7229519/203657) – kleopatra Nov 11 '13 at 13:35
  • 1
    Once you invoke setPreferredSize() the size of the label will never change dynamically again. You need to use setPreferredSize(null). The better option is so use a layout manager that will respect the min/preferred sizes, like a BoxLayout or GrigBagLayout. – camickr Nov 11 '13 at 16:38
  • Thanks for this answer @camickr ! setPrefferedSize(null) is exactly what i needed in my case, although I knwo that a LayoutManager would be better! – Nikolai Dec 14 '13 at 15:21

2 Answers2

2

You can reach what you want using a LayoutManager
Below is a example with GridBag Layout

public class GridBagExample extends JFrame {

    private JPanel      contentPane;
    private JLabel      lblMyLabel;
    private JTextField  textField;
    private JButton     btnChangeMyLabel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    GridBagExample frame = new GridBagExample();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GridBagExample() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 94);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[] { 0, 344, 0 };
        gbl_contentPane.rowHeights = new int[] { 0, 0, 0 };
        gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
        gbl_contentPane.rowWeights = new double[] { 1.0, 1.0, Double.MIN_VALUE };
        contentPane.setLayout(gbl_contentPane);

        lblMyLabel = new JLabel(" My Label");
        GridBagConstraints gbc_lblMyLabel = new GridBagConstraints();
        gbc_lblMyLabel.insets = new Insets(0, 0, 5, 5);
        gbc_lblMyLabel.anchor = GridBagConstraints.EAST;
        gbc_lblMyLabel.gridx = 0;
        gbc_lblMyLabel.gridy = 0;
        contentPane.add(lblMyLabel, gbc_lblMyLabel);

        textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 0;
        contentPane.add(textField, gbc_textField);
        textField.setColumns(10);

        btnChangeMyLabel = new JButton("Change My Label");
        btnChangeMyLabel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                lblMyLabel.setText("This is the new text of my JLabel");
            }
        });
        GridBagConstraints gbc_btnChangeMyLabel = new GridBagConstraints();
        gbc_btnChangeMyLabel.gridwidth = 2;
        gbc_btnChangeMyLabel.gridx = 0;
        gbc_btnChangeMyLabel.gridy = 1;
        contentPane.add(btnChangeMyLabel, gbc_btnChangeMyLabel);
    }

Hope it helps.

Gabriel Câmara
  • 1,249
  • 15
  • 22
0

To set a minimum size, use setMinimumSize(Dimension). In most cases, it is better to place the JLabel in a container with a suitable layout manager, and to set size on it.


Return value of getPreferredSize() is automatically calculated until you set an explicit preferred size. After this, getPreferredSize() will be return with this specific size. If you reset preferred size (by setting it to null), then automatic size will be again available. In your case:

label.setText("Text");
System.out.println(label.getPreferredSize().width); // 25
label.setPreferredSize(new Dimension(50, 20));
System.out.println(label.getPreferredSize().width); // 50
label.setText("New long text");
System.out.println(label.getPreferredSize().width); // 50
label.setPreferredSize(null);
System.out.println(label.getPreferredSize().width); // 77
Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34