下面的示例描述了以下应用程序:
BorderLayout NORTH 上的按钮将带有一些组件的 GridBagLayout 面板添加到 BorderLayout.CENTER 内的 BoxLayout.Y_AXIS。但是点击按钮后,面板出现在中心,而不是被添加到顶部。
public class Test extends JFrame {
public Test() {
super("Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.add(new RecordPanel("text1", "text2"));
panel.revalidate();
}
});
Container container = getContentPane();
container.add(add, BorderLayout.PAGE_START);
container.add(panel, BorderLayout.CENTER);
setSize(300, 500);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
private class RecordPanel extends JPanel {
private JRadioButton radioButton;
private JLabel textLabel1;
private JLabel textLabel2;
public RecordPanel(String text1, String text2) {
super();
radioButton = new JRadioButton();
textLabel1 = new JLabel(text1);
textLabel2 = new JLabel(text2);
initGUI();
}
private void initGUI() {
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
add(radioButton, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
add(textLabel1, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
add(textLabel2, constraints);
}
}
}
使用锚点 ( constraints.anchor = GridBagConstraints.FIRST_LINE_START
) 将单选按钮和一个标签设置到顶部,但第二个标签仍然出现在中心。
如何使面板出现在顶部而不是中心?