Issue
I have created a frame and 2 panels in Java, the first panel have some buttons and the other panel will show the new TextFields. After those textfields are created. I want to get the text in each textfield but i dont know how to get each text if i dont have an specific variable name for each one.
public class GUIListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==boton2){
System.out.println("boton 2");
takeData();
}else if(e.getSource()==boton3){
System.out.println("boton 3");
createTextFields(4);
}
}
}
public void createTextFields(int quantity){
panel2.removeAll();
for(int i =0;i<quantity;i++){
texto = new JTextField("TF # "+i);
panel2.add(texto);
}
panel2.validate();
panel2.repaint();
}
public void takeData(){
System.out.println(texto.getText());
//Only prints the text of the last textfield created
}
Solution
Save all the JTextField
s in a collection or array and return them.
public JTextField[] createTextFields(int quantity) {
panel2.removeAll();
JTextField[] textFields = new JTextField[quantity];
for(int i =0;i<quantity;i++) {
texto = new JTextField("TF # "+i);
panel2.add(texto);
textFields[i] = texto;
}
panel2.validate();
panel2.repaint();
return textFields;
}
Answered By - nylanderDev
Answer Checked By - Willingham (JavaFixing Volunteer)