在Java中实现事件处理时使用`this`关键字
在此语句中,“this”关键字的用途是什么?通过“this”关键字将传递什么引用?如果可能的话,请给我举个例子。这意味着这个对象,如果你写这个语句,这意味着你的类实现了ActionListener 例如:在Java中实现事件处理时使用`this`关键字,java,swing,this,Java,Swing,This,在此语句中,“this”关键字的用途是什么?通过“this”关键字将传递什么引用?如果可能的话,请给我举个例子。这意味着这个对象,如果你写这个语句,这意味着你的类实现了ActionListener 例如: b1.addActionListener(this); 这意味着这个对象,如果你写这个语句,这意味着你的类实现了ActionListener 例如: b1.addActionListener(this); 引用对象的当前实例 假设您的类A实现了ActionListener。然后从您的类
b1.addActionListener(this);
这意味着这个对象,如果你写这个语句,这意味着你的类实现了ActionListener 例如:
b1.addActionListener(this);
引用对象的当前实例
假设您的类A实现了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");
}
}
};
这里之所以使用此选项,是因为currentobject也是一个操作侦听器,它引用对象的当前实例
假设您的类A实现了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");
}
}
};
此处之所以使用此选项,是因为currentobject也是一个动作侦听器可能的重复项question@leigero发现您的问题,下次在Words上发布帖子时不要使用聊天快捷方式。这将指向您正在使用的类的当前实例。可能重复question@leigero发现您的问题,下次在Words上发布帖子时不要使用聊天快捷方式。这指向您正在使用的类的当前实例。“this”表示该对象。@EJP是的,您是对的@ShyamD URW,如果你的问题足够的话,请接受答案。@EJP是的,你是对的@ShyamD URW,如果你的问题足够多,请接受回答谢谢你的回答,你的回答真的很有帮助me@user2578593不客气。。欢迎来到so。。。如果你认为答案有帮助,请投票接受答案当然,一旦我获得足够的声誉,我会的谢谢你,派克,你的答案真的很有帮助me@user2578593不客气。。欢迎来到so。。。如果你认为答案有帮助,请接受答案当然,一旦我获得足够的声誉,我会的