Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Swing:JButton创建新的JTextField_Java_Swing_Jpanel_Jbutton_Jtextfield - Fatal编程技术网

Java Swing:JButton创建新的JTextField

Java Swing:JButton创建新的JTextField,java,swing,jpanel,jbutton,jtextfield,Java,Swing,Jpanel,Jbutton,Jtextfield,您好:)我是JavaSwing的初学者,我无法用谷歌搜索解决方案来解决我的问题。我有一个JPanel,想在按下JButton后动态添加JTextField。我以后如何从他们那里获取text()?我的代码、注释部分工作不正常 变量“counter”统计面板中有多少字段 public class AppPanel extends JPanel { private JTextField tfData[]; private JButton btAdd; private int

您好:)我是JavaSwing的初学者,我无法用谷歌搜索解决方案来解决我的问题。我有一个JPanel,想在按下JButton后动态添加JTextField。我以后如何从他们那里获取text()?我的代码、注释部分工作不正常

变量“counter”统计面板中有多少字段

public class AppPanel extends JPanel {

    private JTextField tfData[];
    private JButton btAdd;
    private int counter = 1;

    public AppPanel() {
            setLayout(null);

            //tfData[counter] = new JTextField();
            //tfData[counter-1].setBounds(20, 20, 250, 20);
            //add(tfData[counter-1]);

            btAdd = new JButton("Add field");
            btAdd.setBounds(280, 20, 120, 20);
            btAdd.addActionListener(new alAdd());
            add(btAdd); 
    }

    class alAdd implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                    //tfData[counter] = new JTextField();
                    //tfData[counter].setBounds(20, 20+20*counter, 250, 20);
                    //add(tfData[counter]);
                    ++counter;
            }
    }
}

由于已存储对文本字段的引用,只需使用此数组查询文本字段的文本:

tfData[counter-1].getText();
将显示上次添加的文本字段的文本

但您确实应该在之前初始化数组,否则将无法向其中添加任何项。我认为这是您在注释添加代码时遇到的主要问题

// think about how many text fields you will need (here: 16)
private JTextField tfData[] = new tfData[16];

如果您使用的是数组,请注意不要超出其界限。但是,正如前面的评论中所建议的那样,它是动态增长的,您不必处理数组边界,甚至可以跳过计数(列表也可以这样做)。

由于您已经存储了对文本字段的引用,只需使用此数组查询文本字段的文本即可:

tfData[counter-1].getText();
将显示上次添加的文本字段的文本

但您确实应该在之前初始化数组,否则将无法向其中添加任何项。我认为这是您在注释添加代码时遇到的主要问题

// think about how many text fields you will need (here: 16)
private JTextField tfData[] = new tfData[16];

如果您使用的是数组,请注意不要超出其界限。但是,正如前面评论中所建议的那样,它会更好,因为它是动态增长的,您不必处理数组边界,甚至可以跳过计数(列表也会这样做)。

您可以参考这个问题,您可以参考这个问题