网格布局有两列,每边都有 50% 的空间,不管组件的实际大小是多少。SetPreferedSize 似乎也不起作用 - 但我不应该需要它,这应该自动完成,对吧?
我可以调整第一行的宽度以适应“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;
}
}
此外,另一个问题是您可以重新调整窗口大小来剪切文本: