b1.addActionListener(this);
在这个语句中,'this
'关键字的用法是什么,通过'this
'关键字传递什么引用?如果可能的话,请举例告诉我。
这
指的是对象的当前实例。
假设你的类A
实现了ActionListener
。 然后从你的类如果你添加侦听器那么你可以使用它,至于继承规则,你的类也是一个侦听器。
class A implements ActionListener{
Button b;
A(){
b1 = new Button();
b1.addActionListener(this);
}
}
这里使用这个是因为当前对象也是一个动作侦听器
"this" 表示此对象,如果您编写此语句,则表示您的类实现了 ActionListener
例如:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class test extends JFrame implements ActionListener {
JButton someButton;
test() {
// create the button
someButton = new JButton();
// add it to the frame
this.add(someButton);
// adding this class as a listener to the button, if button is pressed
// actionPerformed function of this class will be called and an event
// will be sent to it
someButton.addActionListener(this);
}
public static void main(String args[]) {
test c = new test();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.setSize(300, 300);
c.setVisible(true);
c.setResizable(false);
c.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == someButton)
{
JOptionPane.showMessageDialog(null, "you pressed somebutton");
}
}
};