Pass arguments into JButton ActionListener

Sam picture Sam · Mar 29, 2012 · Viewed 23.1k times · Source

I'm looking for a way to pass a variable or string or anything into an anonymous actionlistener ( or explicit actionlistener ) for a JButton. Here is what I have:

public class Tool {
...
  public static void addDialog() {
    JButton addButton = new JButton( "Add" );
    JTextField entry = new JTextField( "Entry Text", 20 );
    ...
    addButton.addActionListener( new ActionListener( ) {
      public void actionPerformed( ActionEvent e )
      {
        System.out.println( entry.getText() );
      }
    });
  ...
  }
}

Right now I just declare entry to be a global variable, but I hate that way of making this work. Is there a better alternative?

Answer

mre picture mre · Mar 29, 2012
  1. Create a class that implements the ActionListener interface.
  2. Provide a constructor that has a JTextField argument.

Example -

class Foo implements ActionListener{
    private final JTextField textField;

    Foo(final JTextField textField){
        super();
        this.textField = textField;
    }
    .
    .
    .
}

Problem?