1

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

2 回答 2

6

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

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);
于 2014-02-10T03:54:11.700 回答
3
  • SpringLayout.NORTH 指定组件边界矩形的上边缘。
  • SpringLayout.SOUTH 指定组件边界矩形的底部边缘。
  • SpringLayout.EAST 指定组件边界矩形的右边缘。
  • SpringLayout.WEST 指定组件边界矩形的左边缘。
  • SpringLayout.BASELINE 指定组件的基线。
  • SpringLayout.HORIZONTAL_CENTER 指定组件边界矩形的水平中心。
  • SpringLayout.VERTICAL_CENTER 指定组件边界矩形的垂直中心。

(如何使用SpringLayout )

使用相同springLayout.putConstraint()的放置在中心,就像你在角落里一样。

于 2014-02-07T08:46:39.320 回答