b1.addActionListener(this);
在此声明中,' this
'有什么用?关键字以及将通过' this
'传递的参考资料关键字?如果可能的话,请举例说明。
答案 0 :(得分:2)
“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");
}
}
};
答案 1 :(得分:2)
this引用当前的对象实例。
说您的班级A
实施ActionListener
。然后从你的类中添加监听器然后就可以使用它,对于继承规则,你的类也是一个监听器。
class A implements ActionListener{
Button b;
A(){
b1 = new Button();
b1.addActionListener(this);
}
}
这里使用它是因为currentobject也是一个动作监听器