Reputation: 16028
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?
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:
Upvotes: 1
Views: 3957
Reputation: 168815
GridLayout
instances in the WEST
(labels) and CENTER
(values) of a BorderLayout
. Add the outer panel to the WEST
or the parent..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