【发布时间】:2014-03-04 12:49:23
【问题描述】:
我正在尝试使用 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);
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发布MCTaRE(经过测试和可读的最小完整示例)。 2) 提供 GUI 的 ASCII 艺术(或带有简单绘图的图像),因为它应该以最小尺寸出现,并且(如果可调整大小)具有额外的宽度/高度。
-
@leigero 请务必添加
@符号以通知此人有新评论。根据您的询问,它是 SSCCE 试图传达的内容的较短版本,所以是的。此外,MCTaRE 托管在 Stack Exchange,而托管 SSCCE 文档的 SSCCE.org 域将在 2 月底永远消失。
标签: java swing layout-manager springlayout