I have several JTextField components on a panel and I want to treat text change events to these components alike in some way.
Instead of having a dedicated DocumentListener for each one, I thought that I would do what I have done with ActionEvents. In short, use the getSource method to see exactly what component I'm dealing with (the one that was modified to fire the actionPerformed method call).
Instead of chasing up the containment chain, you could do something like:
You'll end up with N listeners and not the 1 for which you're asking, but this solution is not "heavy".
posted 16 years ago
What I have is a JTextField that is logically associated with other JTextFields (on the same "row" in a JPanel).
When the text in the first (the trigger) JTextField is modified, I want to toggle the row it is associated with either into, or out of, action (visible or invisible for example).
Only the scpecific row of associated JTextFields should be affected, not the ones in the other rows below or above the JTextField that was used as the trigger.
For example, think of the items below as JTextFields. If T2 is modified, A2, B2, and D2 will be toggled, but not A1, B1, C1, D1 or A3, B3, C3, or D3.
T1 A1 B1 C1 D1 T2 A2 B2 C2 D2 T3 A3 B3 C3 D3
If T1, T2, and T3 each share a common DocumentListener, then how can you determine which trigger ( T1, T2, or T3) was actually modified?
If it were an ActionEvent instead of a DocumentEvent, then you could use the getSource method, but DocumentEvent does not have a getSource.
I know that T1, T2, and T3 could each have their own seperate DocumentEvent so you would know which one was modified, but I have many T# fields, and I would rather not create a distinct DocumentListener for each.
What I've decided to do (unless there is a better way) is create a constructor for my DocumentListener implementing class that takes an indicator of the associated row. I can then inspect that to see what row to update. [ June 10, 2004: Message edited by: Darrin Smith ]
Originally posted by Darrin Smith: What I've decided to do (unless there is a better way) is create a constructor for my DocumentListener implementing class that takes an indicator of the associated row. I can then inspect that to see what row to update.
That's the same as the solution I suggested (you just use a different parameter).
You could always see which one has the keyboard focus, but that seems like a hack. Your solution seems fine.