Swing を使用して Java でフォームを作成しようとしていますが、レイアウトの管理に問題があります。
ダイアログの中央にラベル付きのテキスト フィールドをいくつか配置し、右下に「保存」ボタンと「閉じる」ボタンを配置したいと考えています。
ダイアログの右下にボタンを追加するのは簡単ですが、テキスト フィールドを中央揃えにする方法がわかりません。センターコンポーネントメソッドがなければ、ダイアログウィンドウの中心を計算し、ダイアログのサイズが変更されたときに位置を更新することで、フィールドを整列できるかもしれないと考えました。しかし、私はスイングするのが初めてで、どちらを行うべきかわかりません (または、それが良いアイデアであるかどうかもわかりません)。
Spring Layout Manager を使用してコンポーネントを中央揃えにするにはどうすればよいですか?
public class Main {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}
});
}
}
フレームの外観は次のとおりです。
public class MyFrame extends JFrame {
JLabel label1;
JTextField field1;
JLabel label2;
JTextField field2;
JButton saveButton;
JButton closeButton;
public MyFrame() {
initLookAndFeel();
initFrameProperties();
initContent();
initLayout();
}
private initContent() {
label1= new JLabel("Label 1");
field1= new JTextField();
label1.setLabelFor(field1);
label2= new JLabel("Label 2");
field2= new JTextField();
label2.setLabelFor(field2);
saveButton = new JButton("Save");
closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
this.add(label1);
this.add(field1);
this.add(lebel2);
this.add(field2);
this.add(saveButton);
this.add(closeButton);
}
private void initLayout() {
SpringLayout layout = new SpringLayout();
this.setLayout(layout);
}