java - 在方法中使用 this 关键字引用对象?

标签 java

如何在 mouseEntered 方法中使用 this 关键字来引用对象? 由于 this 关键字接缝引用了 mouseAdapter 类?

public class JButtonx extends JButton {
public String name;
public JButtonx(String xe) {
    this.name = xe;
    this.setText(this.name);
    this.setForeground(new Color(255,255,255));
    this.setBounds(346, 6, 88, 25);
    this.setOpaque(true);
    this.setBackground(new Color(100,100,100));
    this.setFocusPainted(false);

    this.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            //The error occures here.
            this.setBackground(new Color(100,100,100));

        }
    });
}
}

最佳答案

在嵌套类中,您可以省略 this 关键字,而只使用方法或字段的名称。非静态嵌套类可以访问外部类的字段和方法。

this.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        setBackground(new Color(100,100,100));
    }
});

正如其他人所建议的,您可以将类名放在 this 之前,然后调用该方法。这种形式更冗长,可能更容易理解,它还允许您在外部类和嵌套类中具有相同名称的两个方法或字段之间进行指定。

this.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        JButtonX.this.setBackground(new Color(100,100,100));
    }
});

要研究更多关于嵌套类中字段和方法访问的信息,请查看 Java Tutorial .

关于java - 在方法中使用 this 关键字引用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20904522/

相关文章:

Java ImageIO,无法设置像素值?

java - 我们可以在嵌入式Java中使用Lombok吗?

java - Realm 和预期的 BEGIN_OBJECT,但在路径 $[0].location.coordinates[0] 处为 NUMBER

找不到 Javah 错误

java - 如何在Python类中使用全局变量?

java - JAVA中使用字符串的回文

java - 解决 Eclipse 警告 "isn' t 参数化的正确方法是什么?

java - JTable insertRow ArrayIndexOutOfBoundsException

java - 监听器和符号错误问题

java - 如何使用 Guice 播种非作用域命名绑定(bind)?