我有一个包含两个组件的 GridBagLayout:JRadioButton 和 JLabel。标签中的文本因长度而异。这个 GridbagLayout 被添加到 JPanel。因此,当我有很多组件时,它们最终并没有很好地对齐。这就是我的意思:
-----radio btn-label-----
---radio btn-label --
-------radio btn-lbl-----
但我需要以下内容:
-radio btn-label -
-radio btn-label -
-radio btn-lbl -
这就是我的网格现在的样子:
public class MyPanel extends JPanel {
private JLabel info;
private JRadioButton select;
public MyPanel() {
this.achiev = achiev;
achievementInfo = new JLabel();
selectAchiev = new JRadioButton();
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.LINE_START;
add(selectAchiev, constraints);
StringBuilder builder = new StringBuilder();
builder.append("<html><b>").append("some text").append("</b><p>");
builder.append("<i>").append("some more text").append("</i>");
info.setText(builder.toString());
constraints.gridx = 1;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
add(info, constraints);
}
//--------------
JPanel panel = new JPanel(new BoxLayout(), BoxLayout.YAXIS);
for(int i = 0; i < 10; ++i) {
panel.add(new MyPanel());
}