将参数传递给ActionListener [英] Passing Arguments to ActionListener

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

问题描述

public class start implements ActionListener {

    public void actionPerformed(ActionEvent aL) {
      method(arguments);

    }
  }

method(arguments) {
   //stuff
}

我希望JButton告诉程序使用参数stuff启动方法所以我将actionListener放在按钮上面但是actionListener没有可以访问参数,我不知道如何给它们(我查看了oracle文档,无法弄明白)。我试过这个:

I want a JButton to tell the program to start a method using the arguments "stuff" So I put the actionListener above on the button however the actionListener does not have access to the arguments and I don't know how to give it them (I looked at the oracle docs and couldn't figure it out). I tried this:

actionPerformed(ActionEvent aL, stuff) {

这不起作用,我收到错误

and that doesn't work, I get the error

Compute.java:45: error: Compute.start is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
  public class start implements ActionListener {
         ^

我尝试放置一个@Override,但你不能根据编译器覆盖它。那么,我如何将参数提供给ActionListener或者让方法在按钮之外,但只有在按下按钮后才开始工作,但是我在JFrame中使用JProgressBar按钮所在的按钮是使用方法作为计时器的东西所以最好将参数传递给actionListener

And I tried putting an @Override but you can't override that according to the compiler. So, how can I give the arguments to the ActionListener or have the method outside of the button but only start working once the button is pressed, however I am using a JProgressBar within the JFrame the button is in which uses the method as it's timer thing so it would be preferable to pass the arguments to the actionListener

推荐答案

您可以通过构造函数传递参数。但当然这意味着只有在创建 ActionListener 时才能传递参数。

You can pass the arguments by constructor. But of course it means with this way you can pass the arguments only when creating the ActionListener.

public class Start implements ActionListener {

    SomeType arguments;
    public Start (SomeType arguments) {
         this.arguments = arguments;
    }

    public void actionPerformed(ActionEvent aL) {
        method(arguments);    
    }
}

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

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