按钮的位置转到一个奇怪的位置(SpringLayout)

时间:2016-08-04 23:00:25

标签: java swing layout-manager springlayout

我正在制作一个java应用程序,您可以通过表单添加新帐户,我使用SpringLayout因为它看起来很整洁,但是在添加带有文本的JTextFields之后,按钮保持在左上方它不应该到那里,我使用SpringUtilities (https://docs.oracle.com/javase/tutorial/uiswing/examples/layout/SpringGridProject/src/layout/SpringUtilities.java

package dinges.Containers;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import dinges.Utilities.SpringUtilities;

@SuppressWarnings("serial")
public class Addnew extends JPanel {

    String[] options = {"User", "Accountant", "Administrator", "Developer"};

    /**
     *  > Add a text input for the following:
     *  > Id, Name, last name, current balance, and the state. But this has to be in order of the new Account.
     *  > we're just going to be using JTextFields, a JButton for saving and JLabels for writing what it is
     * 
     **/

    public Addnew() {
        // frame size is WIDTH =   280     ,      HEIGHT =     480
        SpringLayout layout = new SpringLayout();
        setLayout(layout);

        JButton save = new JButton("Save data");
        JTextField name = new JTextField(15);
        JTextField lastname = new JTextField(15);
        JComboBox<String> accounttype = new JComboBox<String>(options);
        JLabel label1 = new JLabel("First name: ", JLabel.TRAILING);
        JLabel label2 = new JLabel("Last name: ", JLabel.TRAILING);
        JLabel label3 = new JLabel("Account type: ", JLabel.TRAILING);
        JLabel label4 = new JLabel("Save data: ", JLabel.TRAILING);
        label1.setLabelFor(name);
        label2.setLabelFor(lastname);
        label3.setLabelFor(accounttype);




        add(label1);
        add(name);
        add(label2);
        add(lastname);
        add(label3);
        add(accounttype);
        add(save);
        add(label4);

        SpringUtilities.makeCompactGrid(this, 3, 2, 6, 6, 6, 6);
    }

}

这看起来像这样:

enter image description here

但是按钮应该在JComboBox下面,它的JLabel应该像其他按钮一样定位。

这里的问题在哪里?我现在已经把东西转了一段时间,但我真的找不到它。

2 个答案:

答案 0 :(得分:1)

  

按钮位于左上方

应该在哪里?

我猜它应该在底部,但你应该指出这是你问题的一部分,因为我们不介意读者,也不知道你在想什么。

  

我正在使用SpringUtilities

您是否告诉SpringUtilities您需要多少行/列?

您是否修改了演示代码中的参数,或者只是在不更改演示代码的情况下复制演示代码?

答案 1 :(得分:-1)

看起来你没有正确设置正确的行数

    // SpringUtilities.makeCompactGrid(p, rows, cols, initX, initY, xPad, yPad); 
    int numPairs = options.length; // 4
    SpringUtilities.makeCompactGrid(p, numPairs, 2, 6, 6, 6, 6);