Search code examples
javaswingjtextfielddocumentlistener

Listening to many JTextFields and calculate value sum in a Row


I have an application that gets input from user;
it has 8 rows of JTextFields with 3 columns:

+-----------+-----------+-----------+
| Field 1-1 | Field 1-2 | Field 1-3 |
+-----------+-----------+-----------+
| Field 2-1 | Field 2-2 | Field 2-3 |
+-----------+-----------+-----------+
| Field 3-1 | Field 3-2 | Field 3-3 |
+-----------+-----------+-----------+

In each row while user changes first or second field the sum of new values must be written in third field.
For example when user changes Filed 1-1 & Field 1-2 sum of them must be calculated and shown in Field 1-3 and so on for other rows.
I wrote a Class that implements DocumentListener and and named it listenerClass & called .getDocument().addDocumentListener(new listenerClass) for all of JTextFields in column 1 & 2 ;
Now in listenerClass I need to know which JTextField called listenerClass to be able determine wich fields must be added and result must be written in which JTextField.

How Can I find out which JTextField called DocumentListener ?
Is there any better method to do this?
Thanks


Solution

  • You have two options here:

    • brute force: just one listener instance that will compute 8 sums and update 8 text fields
    • smart: pass to your listener class constructor 3 text fields and then instantiate a differente listener for each row