JButton addActionListener(this);

时间:2014-02-05 03:11:08

标签: java awt jbutton this actionlistener

我很好奇为什么将一个actionListener添加到JButton将(this)作为一个参数,在Java文档中它表示addActionListener将(ActionListener l)作为参数。它们是不同的参数,我感到困惑。

以下是我正在使用的Java文档的链接:http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html#addActionListener(java.awt.event.ActionListener)

例如我做不到:

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

public class AddButton extends JButton implements ActionListener {

public AddButton(String name) {
    super(name);
    this.addActionListener(ActionListener l);
}

public void actionPerformed(ActionEvent e)  {
    System.out.println("Worked so far!");
}

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

以下是我通常使用的内容:

import javax.swing.*;
import java.awt.*;
public class MainClass extends JFrame{
private JButton chooseFile;
public MainClass(){// Constructor
super("Your Title");
chooseFile = new JButton("Choose File");
HandlerClass handler = new HandlerClass();
chooseFile.addActionListener(handler);
}

private class HandlerClass implements ActionListener {
    public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null,"Button has been clicked");
}
}
}

希望这会对你有所帮助。这一直对我有用。