I am writing a program that contains a JButton. Every time the button is clicked, a new JTextField is added to a JPanel.
My problem is that, after the user has created all the JTextFields and filled them with information, I need to get the text of each field. How can I get access to the JTextFields when they are dynamically generated, as they don’t have instance names? Is there a better way to get the text of each one, without knowing their instance name.
Here is the code of the actionPerformed event of the JButton…
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
JTextField x = new JTextField();
x.setColumns(12);
p.add(x);
validate();
}
You say you want to get the text from each field. So, when you create the new instances
x, why don’t you keep a collection of them, such as adding theJTextFieldsto anArrayList?Alternatively, assuming that
pis aJPanel, you should be able to get all the children, which would be theJTextFieldsthat you’re adding. Try usinggetComponents()like so…