我正在尝试使用Swing在Java中创建一个Form,但是在管理布局方面遇到困难。

我想在对话框的中央有一些带有标签的文本字段,并在右下方有“保存”和“关闭”按钮。

将按钮添加到对话框的右下方很简单,但是我不确定如何居中对齐文本字段。我发现,如果没有中心组件方法,那么我可以通过计算对话框窗口的中心,然后在调整对话框大小时更新位置,来对齐字段。但是我是新手,我不确定该怎么做(或者这是否是个好主意)。

如何使用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);
    }

最佳答案

您可以通过添加约束将组件的水平中心设置为与内容窗格的“水平中心”相同的约束来使组件居中。调整窗口大小时,这将自动更新组件位置。

SpringLayout layout = new SpringLayout();

// For Horizontal Alignment
layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, component, 0, SpringLayout.HORIZONTAL_CENTER, contentPane);

// For Vertical Alignment
layout.putConstraint(SpringLayout.VERTICAL_CENTER, component, 0, SpringLayout.VERTICAL_CENTER, contentPane);

setLayout(layout);

09-30 15:37
查看更多