将参数传递给JButton ActionListener

Sam*_*Sam 4 java swing jbutton actionlistener

我正在寻找一种方法将变量或字符串或任何东西传递给JButton的匿名actionlistener(或显式actionlistener).这是我有的:

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() );
      }
    });
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我只是声明entry是一个全局变量,但我讨厌这样做的方式.还有更好的选择吗?

mre*_*mre 10

  1. 创建一个实现该ActionListener接口的类.
  2. 提供具有JTextField参数的构造函数.

示例 -

class Foo implements ActionListener{
    private final JTextField textField;

    Foo(final JTextField textField){
        super();
        this.textField = textField;
    }
    .
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

问题?