将参数传递给JButton ActionListener [英] Pass arguments into JButton ActionListener

查看:510
本文介绍了将参数传递给JButton ActionListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法将变量或字符串或任何东西传递给JButton的匿名actionlistener(或显式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?

推荐答案


  1. 创建一个实现的类ActionListener interface。

  2. 提供一个具有 JTextField 参数的构造函数。

  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?

这篇关于将参数传递给JButton ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆