Java 将参数传递到JButton ActionListener

Java 将参数传递到JButton ActionListener,java,swing,jbutton,actionlistener,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 ); ..

我正在寻找一种方法,将变量、字符串或任何内容传递到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
是一个全局变量,但我讨厌这样做。有更好的选择吗

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

  • 范例-

    问题?

    在这种情况下,使用Action和AbstractAction可能更好,在这里您可以做这类事情

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

    如果您在本地将变量声明为final,那么侦听器将能够访问它

    最终JTextField条目=新JTextField(“条目文本”,20);
    ...
    addButton.addActionListener(新的ActionListener(){
    已执行的公共无效操作(操作事件e)
    {
    System.out.println(entry.getText());
    }
    });
    ...
    
    2种方式

  • 制作
    条目
    最终
    ,以便可以在匿名类中访问它

    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() );
          }
        });
      ...
      }
    
  • 条目
    设为字段

    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() );
          }
        });
      ...
      }
    

  • 我以本地人的身份写了这段代码,这样它就可以工作了,我的意思是这就是我想要它工作的方式。我使用它的方式是全局性的。谢谢你提供的信息,效果很好,让我更好地理解了这一切是如何联系在一起的。不过,我也遇到了同样的问题,并把它作为一个有用的answare。2)基本上就是我如何让它工作的。我还没有试过,但我还是按照mre的建议做了。我想我还没有用够
    final
    来真正掌握用法,谢谢。
    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() );
          }
        });
      ...
      }