我正在尝试使用 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);
}