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).