首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java中实现事件处理时使用`this`关键字

在Java中实现事件处理时使用`this`关键字
EN

Stack Overflow用户
提问于 2013-07-13 14:11:19
回答 2查看 1.3K关注 0票数 1
代码语言:javascript
运行
复制
 b1.addActionListener(this);

在这条语句中,'this‘关键字的用法是什么,通过'this’关键字传递的引用是什么?如果可能的话,请告诉我例子。

EN

回答 2

Stack Overflow用户

发布于 2013-07-13 14:18:31

" this“表示此对象,如果您编写此语句,则表示您的类实现了ActionListener

例如:

代码语言:javascript
运行
复制
    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");
        }
    }
};
票数 2
EN

Stack Overflow用户

发布于 2013-07-13 14:26:39

this引用object的当前实例。

假设您的类A实现了ActionListener。然后从你的类中,如果你添加了listener,那么你可以使用这个,至于继承规则,你的类也是一个listener。

代码语言:javascript
运行
复制
class A implements ActionListener{
    Button b;
    A(){
         b1 = new Button();
         b1.addActionListener(this);
    }
}

在这里使用它是因为currentobject也是一个操作侦听器

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17627519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档