以下のサンプルでは、次のアプリについて説明します。
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
ラジオ ボタンと 1 つのラベルを一番上に設定しますが、2 番目のラベルはまだ中央に表示されます。
パネルを中央ではなく上部に表示するにはどうすればよいですか?