Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments into JButton ActionListener

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?

like image 406
Sam Avatar asked Dec 07 '22 15:12

Sam


1 Answers

  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?

like image 195
mre Avatar answered Dec 09 '22 04:12

mre