【问题标题】:How do I access "this" in an anonymous function? [duplicate]如何在匿名函数中访问“this”? [复制]
【发布时间】:2015-10-08 04:41:00
【问题描述】:

我在编写匿名函数时无法访问this

public class Game extends JPanel {
    public void action() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                this.repaint();
            }
        }).start();
    }
    @Override
    public void paint(Graphics g) {
        // Paint stuff
    }
}

我无法声明我的类的新实例,因为我无法将类设置为我的新类实例而不会出现静态/非静态错误。

【问题讨论】:

  • Game.this.repaint()
  • @MadProgrammer 非常感谢!
  • 对不起,我不知道它叫内部类。
  • 从技术上讲,在您的情况下,它是一个匿名类,但对于实例内部类也是如此;)

标签: java static non-static


【解决方案1】:

当你写作时

 public void action() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                this.repaint();
            }
        }).start();
    }

由于你在写匿名​​内部类Runnable,所以你写this.repaint().时指的是Runnable匿名类

引用Game类重绘,语法为Game.this.repaint()

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2012-03-22
    • 2010-11-08
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多