SpringLayout的问题

时间:2019-02-23 21:30:18

标签: java swing layout-manager springlayout

我已经写了一些代码,但是当我运行它时,id并不能像我想要的那样工作:它仅在左上角显示数组中的最后一个元素

public class AddClient extends JPanel {
    String title = "title";
    String description = "desc";

    SpringLayout layout = new SpringLayout();

    String[] label_text = new String[] {"Name", "Surname", "VAT"};
    JLabel[] label_left = new JLabel[label_text.length];
    JTextField[] field_left = new JTextField[label_text.length];

    public AddClient() {
        setLayout(layout);
        compone();

        Main.tab.addTab(title, null, this, description);
    }

    public void compone() {
        for(int i = 0; i < label_text.length; i++) {
            label_left[i] = new JLabel(label_text[i]);
            if(i == 0)
                layout.putConstraint(SpringLayout.NORTH, this, 5, SpringLayout.NORTH, label_left[i]);
            else
                layout.putConstraint(SpringLayout.SOUTH, label_left[i-1], -5, SpringLayout.NORTH, label_left[i]);
            add(label_left[i]);
        }
    }
}

结果:

https://i.stack.imgur.com/nQdz4.png

我如何将所有元素设置为彼此相邻(如下所示)?

 _______________________________________
|Name                                   |
|Surname                                |
|VAT                                    |
|                                       |
|                                       |
|                                       |
|                                       |
|                                       |
|                                       |
|                                       |
|_______________________________________|

1 个答案:

答案 0 :(得分:0)

解决了!! 我不知道为什么,但是它只能像这样工作(将第一个元素切换为第二个元素):

layout.putConstraint(SpringLayout.NORTH, label_left[i], -5, SpringLayout.SOUTH, label_left[i-1]);

代替:

layout.putConstraint(SpringLayout.SOUTH, label_left[i-1], -5, SpringLayout.NORTH, label_left[i]);