如何从 Java 中动态生成的文本字段获取数据?

How do I get data from dynamically generated text fields in Java?

我已经使用 for 循环生成了 N 个文本字段(N 是用户输入的输入数)。我想获取用户在这些文本字段中输入的数据并将其保存在 ArrayList 中。我不知道这些字段的名称,所以有什么方法可以获取文本字段的名称吗?或者如何将 N 个文本字段中的数据存储到 ArrayList 并使用该 ArrayList 中的值。这是我的代码:

public class FCFS extends JFrame implements ActionListener{
    JButton btn1,btn2,b;
    JTextField tf1,tf2;
    JPanel p;
    Container c;
    ArrayList arr=new ArrayList();
    public FCFS(){
        //super("FCFS");
        c=getContentPane();
        p=new JPanel();
        JLabel lbl1=new JLabel("Enter number of processes:");
        p.add(lbl1);
        tf1=new JTextField(20);
        p.add(tf1);
        btn1=new JButton("Enter");
        btn1.addActionListener(this);
        p.add(btn1);
        c.add(p);

    }
    public static void main(String args[]){
        FCFS obj=new FCFS();
        obj.setVisible(true);
        obj.setSize(300,500);
        obj.setDefaultCloseOperation(3);

    }
    @Override
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==btn1){
            p.removeAll();
            int a=Integer.parseInt(tf1.getText());
            for(int i=1;i<=a;i++){
                p.add(new JLabel("Enter Burst for Process "+i+":"));
                tf2=new JTextField(20);
                p.add(tf2);
                arr.add(tf2.getText());
                c.add(p);
                revalidate();
                repaint();
            }
            b=new JButton("Show");
            p.add(b);
            c.add(p);
            revalidate();
            repaint();
            b.addActionListener(this);
        }
        else if(ae. getSource()==b){
            System.out.println("Hello");
            System.out.println(arr);
        }
    }
}

您不需要字段的名称,您需要字段本身。您可以遍历 Panel,找到所有的文本字段,也可以将它们保存在数组中,然后在需要时提取它们的值:

@Override
public void actionPerformed(ActionEvent ae){
    if(ae.getSource()==btn1){
        p.removeAll();
        int a=Integer.parseInt(tf1.getText());
        for(int i=1;i<=a;i++){
            p.add(new JLabel("Enter Burst for Process "+i+":"));
            tf2=new JTextField(20);
            p.add(tf2);
            arr.add(tf2);
        }
        b=new JButton("Show");
        p.add(b);
        c.add(p);
        revalidate();
        repaint();
        b.addActionListener(this);
    }
    else if(ae.getSource()==b){
        System.out.println("Hello");
        ArrayList texts=new ArrayList();
        for (Object textField : arr) {
            texts.add(((JTextField)textField).getText();
        }
        System.out.println(texts);
    }
}