Search code examples
javaswingvariablesdynamicjtextfield

Java: change a variable depending on dynamically generated text field name?


I have an ArrayList of TrainingClass objects with a variable "priority".

I am making a settings frame, where for each element currently in the ArrayList I make a TextField where the user sets priority.

This is how it is generated

for (TrainingClass tclass : mTrainingClasses) {
                  //Loop the ArrayList
        JTextField txtPriority = new JTextField(3);
        txtPriority.setBounds(10,10,100,20);
        txtPriority.setText("" + tclass.getPriority());
        getContentPane().add(txtPriority);
 }

Now I would add a change listener, but...

Once I know which field has been changed, how can I access the proper element of the ArrayList mTrainingClasses?

In php, for example, I would simply make something like:

 $mTrainingClasses->$changed_field->setPriority($new_value);

But, as far as I understand, I can’t do this in Java. So, how should I proceed?

Do I need to manually set the field name and listener for each element? I’m sure there is some other solution, but I have no idea at this point.

(I know I could use an ArrayList for the fields as well, such as

txtPriority.add(new JTextField(3));

But in this case, how do I know which index corresponds to the field that has been changed? )


Solution

  • Have a list of Text Fields

    List<JTextField> textFields = new ArrayList<JTextField>();
    

    Change the loop like the following where you add all text fields to above list

    for (TrainingClass tclass : mTrainingClasses) {
            //Loop the ArrayList
            JTextField txtPriority = new JTextField(3);
            txtPriority.setBounds(10,10,100,20);
            txtPriority.setText("" + tclass.getPriority());
            getContentPane().add(txtPriority);
            textFields.add(txtPriority);
    }
    

    In your listener you can do the following

    mTrainingClasses.get(textFields.indexOf((JtextField) event.getSource()));
    

    The above will return the TrainingClass which got changed.