Java Swing:JButton创建新的JTextField [英] Java Swing: JButton creates new JTextField(s)

查看:162
本文介绍了Java Swing:JButton创建新的JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好:)我是Java Swing的初学者,但我无法通过Google解决我的问题.我有一个JPanel,并且想要在按下JButton之后动态添加JTextField.以后如何从他们那里获取Text()?我的代码已注释,部分无法正常工作.

Hello :) I am beginner in Java Swing and I can't google solution for my problem. I have a JPanel and want to add JTextField(s) dynamically after pressing a JButton. And how can I getText() from them later? My code, commented part isn't working properly.

变量计数器"计算我在面板中有多少个字段.

Variable 'counter' counts how many fields I have in panel.

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;
            }
    }
}

推荐答案

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

As you're already storing references to your text fields, just use this array to query the text of the text fields:

tfData[counter-1].getText();

将显示最后添加的文本字段的文本.

will show you the text of the last added text field.

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

But you really should initialise your array before, otherwise you won't be able to add any items to it. I think that was your main problem as you commented out your adding-code.

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

如果使用数组,请注意不要超出数组的范围.但是更好的使用列表因为它是动态增长的,所以您不必在注释中提出建议,甚至不必处理数组边界,甚至可以跳过计数(列表也为您完成了此操作).

If you're using arrays, watch for not breaking over its bounds. But better use a list as proposed in the comments before as it grows dynamically and you won't have to deal with array bounds and can even skip counting (the list does that for you, too).

这篇关于Java Swing:JButton创建新的JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆