当前位置: 代码迷 >> Eclipse >> 关于this的用法,不是很懂,求指点
  详细解决方案

关于this的用法,不是很懂,求指点

热度:62   发布时间:2016-04-23 02:01:16.0
关于this的用法,不是很懂,求指导
import java.awt.*;
import java.awt.event.*;
public class ActionEvent_2 extends Frame implements ActionListener{
    Panel p; //创建面板和按钮
    Button br,bl,bg;
ActionEvent_2() {

super("ActionEvent 本类中实现测试");
p = new Panel();
//创建三个事件源
br = new Button("红色");
bg = new Button("绿色");
bl = new Button("蓝色");
p.add(br);//添加按钮到面板
p.add(bg);
p.add(bl);
add(p, "North");//添加面板到框架

//注册事件侦听器:同一个对象
br.addActionListener(this);
bg.addActionListener(this);
bl.addActionListener(this);
//使用内部匿名类关闭窗口
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
        });
//设置窗口大小和可视性
setSize(300,200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {//实现接口方法
String btnLabel=e.getActionCommand();
if (btnLabel.equals("红色")){
setBackground(Color.RED);
}else if (btnLabel.equals("绿色")){
setBackground(Color.GREEN);
}else if (btnLabel.equals("蓝色")){
setBackground(Color.BLUE);
}
}

public static void main(String argc[]) {
new ActionEvent_2();//调用构造方法
}
}

这是一个简单的界面设计,然后在
//注册事件侦听器:同一个对象
br.addActionListener(this);
bg.addActionListener(this);
bl.addActionListener(this);
这段的this指的是什么?关于this的用法有点模糊
------最佳解决方案--------------------
this代表当前类的实例,当前类也就是ActionEvent_2,它实现了ActionListener接口所以可以作为事件监听器,当事件发生时自动调用actionPerformed方法(这个方法是在ActionListener中定义的,本类实现的)
------其他解决方案--------------------
this指当前对象,
就好比“我”这个标识符,指的就是你自己,你这个人,
而“人”,就是个类,实例化后的对象就是一个个人,你就是这对象中的一个
this就是“我”,就是这个实例化的对象的自我称谓
------其他解决方案--------------------
this应该代表的是 ActionListener吧
------其他解决方案--------------------
我在忘了是哪本书上看到过一句话,是这样解释this的:
this永远指向实例本身。
希望对您有帮助。这个应该对java或C++都一样。
------其他解决方案--------------------
this指的是Panel的实力对象p,就是注册监听器
  相关解决方案