Search code examples
javaswinglayout-managerspringlayout

Issue with SpringLayout


I have written some code, but when I run it, id doesn't work like I wanted: it displays only the last element in the array on the top-left corner

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]);
        }
    }
}

result:

https://i.sstatic.net/nQdz4.png

How can I set all the elements to be one under each other (like below)?

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

Solution

  • Solved!! I don't know why but It works only like this (switching the first element with the second):

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

    instead of:

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