如何在使用侦听器时将参数放在actionPerformed方法中

时间:2014-05-11 16:18:41

标签: java parameters action listener

假如我创建了一个新类并且放置了一个我想在屏幕上实现其他效果的JButton。但是,那件事是在另一个班级的其他地方。如何在actionPerformed方法中添加某种参数?这是一个例子:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class button2 implements ActionListener{
  public void buttton2(final Screen screen){
    JButton test = new JButton("Hello");
    test.addActionListener(this);
  }

      //How do I add a parameter in here?
  public void actionPerformed(ActionEvent arg0, Screen screen) {
    screen.repaint();

  }


}

还是有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

将屏幕存储在字段中:

public class Button2 implements ActionListener{

    private Screen screen;

    public Button2(final Screen screen) {
        this.screen = screen;
        JButton test = new JButton("Hello");
        test.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event) {
        screen.repaint();
    }
}