将文本字段名称分配给可变数量的文本字段

时间:2013-09-16 20:40:41

标签: java swing variables

我的程序首先提示用户输入他们想要绕轨道运行的质量数

public class textEvent1 implements ActionListener {    //action listener for "how many masses?"
        public void actionPerformed (ActionEvent e) {
            n = (int)(Double.parseDouble(massNumField.getText()));


            submit1.setVisible(false);          //removes text event 1 text from screen
            massNumLabel.setVisible(false);
            massNumField.setVisible(false);

然后根据这些信息我创建了那么多标签和文本字段

for(int i=1; i<=n; i++) {                                  //adds text event 2 text to the screen
                    massLabel = new JLabel("How much mass does Mass " +i+ " have? ");
                    massField = new JTextField(5);

                    xCorLabel = new JLabel("What is mass "+i+"'s starting x-coordinate?");
                    xCorField = new JTextField(5);

                    yCorLabel = new JLabel("what is mass "+i+"'s starting y-coordinate?");
                    yCorField = new JTextField(5);

                    xVelLabel = new JLabel("What is mass "+i+"'s starting x velocity?");
                    xVelField = new JTextField(5);

                    yVelLabel = new JLabel("What is mass "+i+"'s starting y velocity?");
                    yVelField = new JTextField(5);

                    add(massLabel);
                    add(massField);

                    add(xCorLabel);
                    add(xCorField);

                    add(yCorLabel);
                    add(yCorField);

                    add(xVelLabel);
                    add(xVelField);

                    add(yVelLabel);
                    add(yVelField);
                }

现在我的问题是从这些文本字段中读取另一个actionlistner(提交按钮)并将输入的值分配给数组。由于我不知道会有多少质量,我不知道会有多少文本字段,每个文本字段基本上都有相同的名称,如何在文本字段的名称与文本字段同名时指定为mass2的质量输入的值。所有其他文本字段?

1 个答案:

答案 0 :(得分:0)

对您需要的每条数据使用List<JTextField>

因此,向您的类添加实例变量:

List<JTextField> masses, xCors, yCors, xVels, yVels;

初始化它们(ArrayLists可能在这里工作正常),然后在创建JTextFields的actionPerformed方法中,将它们逐个添加到列表中:

for (int i = 1; i <= n; i++) {
    massLabel = new JLabel("How much mass does mass " +i+ " have? ");
    massField = new JTextField(5);
    masses.add(massField);

    /* .. initialize all other fields similarly, adding them to the Lists */

如果要从文本字段中读取/赋值的值,可以使用masses.get(i)从列表中访问它们。