David
David

Reputation: 16028

GridLayout not resizing to fit components

The grid layout has two columns and is giving 50% space to each side, no matter what size the components actually are. SetPrefferedSize doesn't seem to work either - but I shouldn't need it, this shold be done automatically, right?

enter image description here

Can I make the first row's width to resize to fit "SomeOtherLongText3:"?

SSCCE:

package test;

import java.awt.*;
import javax.swing.*;

public class test {

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        JPanel detailsPanel = new JPanel();
        detailsPanel.setLayout(new GridLayout(0, 2, 15, 0));

        // Add to left side (WEST)
        frame.add(detailsPanel, BorderLayout.WEST);

        // Add some labels:
        detailsPanel.add(getLabel("Some text:"));
        detailsPanel.add(new JLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc id mauris "));


        detailsPanel.add(getLabel("Some text 2:"));
        detailsPanel.add(new JLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc id mauris "));

        detailsPanel.add(getLabel("Some other text 3:"));
        detailsPanel.add(new JLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc id mauris "));

        frame.setSize(new Dimension(900, 100));
        frame.setVisible(true);
        frame.pack();
    }

    public static JLabel getLabel(String text)
    {
        JLabel lbl = new JLabel(text);
        lbl.setHorizontalAlignment(SwingConstants.TRAILING);
        return lbl;
    }

}

Also, another problem is that you can just re-size the window to cut the text: enter image description here

Upvotes: 1

Views: 3957

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Layout Strategies

  1. Put 2 single column GridLayout instances in the WEST (labels) and CENTER (values) of a BorderLayout. Add the outer panel to the WEST or the parent..
  2. Use a GroupLayout. That might be better since you can use HTML/CSS to limit the width of the values and force them to multiple lines.

Upvotes: 4

Related Questions