fartagaintuxedo fartagaintuxedo - 5 months ago 10x
Java Question

Add a generic ActionListener to many JButtons or JComponents or JTextFields

[ First of all i have read this answer but i understand mine is different Add actionListener to a lot of JButton ]

I have a series of

and i need to do something when their values are updated. Usually i need to do
myAction(JTextField jt)
with all of them.

Right now i use this code to do it, but i have to make an instance of this code for each one of my
and i want to do it only once.

myJTextField1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//change some value here!
//repeat for myJTextFields-2-to-9

This what i have tried but it doesn't work because
is not accessible.

void addListener(JTextField jt){
jt.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
//change some value here!

I also tried something like
jt.addActionListener(new myListener implements ActionListener (jt){
but i don't really know how to something like that.


First create a generic ActionListener which extracts the JTextField on which the action occurred from the event:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {

or shorter as lambda

ActionListener listener = e -> myAction((JTextField)e.getSource());

and then register it on your textfields: