如何在 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/