将参数传递给JButton ActionListener

4
我正在寻找一种方法来将变量、字符串或其他内容传递到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() );
      }
    });
  ...
  }
}

我现在只是声明entry为全局变量,但我不喜欢这种方法使其工作。有更好的替代方案吗?

4个回答

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

示例 -

class Foo implements ActionListener{
    private final JTextField textField;

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

有问题?


1
问题:Java新手。感谢提供的信息,非常有帮助,让我更好地理解了它们之间的关系。 - Sam
然而,我仍然遇到了同样的问题,并得到了这个有用的答案。 - Einar Sundgren

3

两种方法

  1. make entry final so it can be accessed in the anonymous class

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

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

  1. 基本上就是我让它工作的方式。我还没有尝试过1),但我已经按照mre的建议让它工作了。我还没有足够使用“final”来真正掌握它的用法,谢谢。
- Sam

1
也许在这种情况下最好使用Action和AbstractAction,您可以在其中执行那种操作。

1

从我在这里看到的代码来看,entry不是全局变量。它是addDialog()方法中的局部变量。我是否误解了你的意思?

如果您将变量声明为final,则侦听器将能够访问它。

    final JTextField entry = new JTextField( "Entry Text", 20 );
    ...
    addButton.addActionListener( new ActionListener( ) {
      public void actionPerformed( ActionEvent e )
      {
        System.out.println( entry.getText() );
      }
    });
  ...

我将这段代码片段写成本地的,以便它能够工作。我的意思是这就是我想要它工作的方式。而我使用它的方式是全局的。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接