从矢量或数组创建动态表单

时间:2015-01-16 09:28:15

标签: java arrays swing

首先,我是java的新手。 我想基于Arrays动态生成表单,我能够生成字段,但我不知道如何阅读它们,我找不到像文本字段索引之类的东西。 所以基本上我问的是如何从没有引用的TextField组件中读取值。 JTextField myText = new JTextField()vs new JTextField(),添加到面板 下面是一个简单的代码示例,欢迎任何想法。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame{
    private JPanel p1 = new JPanel();
    private JButton btn = new JButton("Read Data");

    public Test(){
        super("Dynamic Form");
        setLayout(new GridLayout(4,2));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Declare the Array with fields
        String[] fList = new String[3];
        fList[0] = "id";
        fList[1] = "firstName";
        fList[2] = "lastName";

        //Iterate fields array and add elements
        for(int i = 0; i<fList.length; i++){
            add(new JLabel(fList[i]));
            add(new JTextField("field: "+fList[i]));
        }

        add(p1);
        add(btn);

        btn.addActionListener(
            new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent ev){
                    String id = "id field value is: "; // + some code to get actual text field value
                    String firstName = "firstName field value is: "; // + some code to get actual text field value
                    String lastName = "lastName field value is: "; // + some code to get actual text field value

                    System.out.println(id+ " " + firstName + " " + lastName);
                }
            }
        );

        pack();
        setLocationRelativeTo(null);
        setResizable(true);
        setVisible(true);
    }

    public static void main(String [] args){
        new Test();
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在某处存储对这些文本字段的引用。

List<JTextField> fields = new ArrayList<>();

...

for(int i = 0; i<fList.length; i++){
        JTextField field= new JTextField("field: "+fList[i]);
        add(new JLabel(fList[i]));
        add(field);
        fields.add(field);
}

现在您可以从字段列表中访问它们:

public void actionPerformed(ActionEvent ev){
    String id = "id field value is: " + fields.get(0).getText(); 
    String firstName = "firstName field value is: " + fields.get(1).getText(); 
    String lastName = "lastName field value is: " + fields.get(2).getText(); 

    System.out.println(id+ " " + firstName + " " + lastName);
}