Search code examples
javamultithreadingarraylistactionlistenerjtextfield

put data from jtextfields into arraylist on JButton click (Actionlistener)


Sorry if my explanation of my problem is a bit clumsy.

Well, I'm trying to add X amount of JTextFields and add the content (int) of each of these into an arrayList. I want to send the arraylist with this information on click of my submit button.

So here is the loop, which creates the JTextFields and was supposed to add data from the fields to the arraylist.

If I enter antalVare = new JTextField("0"),
the 0 will be added to the arraylist, 

but it should fill up the arraylist with the data from the JTextFields again on click of my JButton. How can i do this? I tried different ways using a Thread but failed.

    kundeOrdreArrayList = new ArrayList<String>();

    alleVarerList = kaldSQL.alleVarer(connectDB);

    try {
        while (alleVarerList.next()) {
            antalVare = new JTextField();

            innerPanel.add(new JLabel(alleVarerList.getString(2) + " ("
                    + alleVarerList.getString(3) + ",- kr.)"));
            innerPanel.add(antalVare);
            innerPanel.add(new JLabel(""));
            kundeOrdreArrayList.add(antalVare.getText());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    innerPanel.add(new JLabel(""));
    innerPanel.add(submit);
    innerPanel.add(new JLabel(""));

And here's my ActionListener:

if (a.getSource().equals(submit)) {
        // DO SOMETHING ?


            }

Solution

  • In your first snippet of code, you the values you add to kundeOrdreArrayList are the values of the text fields have at this time. These value is not updated when the text fields are changed afterwards.

    So, in your ActionListener, you need to iterate again over all your JTextFields. To do this, first change your first snippet of code to keep track of all the JTextFields you have. So, add a new field "ArrayList textfields" to your class, then (marked the changed lines with // ++

    textfields = new ArrayList<JTextField>(); // ++
    
    try {
        while (alleVarerList.next()) {
            antalVare = new JTextField();
            textfields.add(antalVare); // ++
    
            innerPanel.add(new JLabel(alleVarerList.getString(2) + " ("
                    + alleVarerList.getString(3) + ",- kr.)"));
            innerPanel.add(antalVare);
            innerPanel.add(new JLabel(""));
            kundeOrdreArrayList.add(antalVare.getText());
        }
    

    Now, in your ActionListener, clear kundeOrdreArrayList and add the values from all the JTextFields again:

      if (a.getSource().equals(submit)) {
          kundeOrdreArrayList.clear();
          for (JTextField field : textfields) {
               kundeOrdreArrayList.add(field.getText());
          }
      }