如何从匿名类中访问封闭的类实例变量? [英] How can I access enclosing class instance variables from inside the anonymous class?

查看:138
本文介绍了如何从匿名类中访问封闭的类实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从匿名类的方法中访问实例变量

How do I access instance variables from inside the anonymous class's method ?

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            // How do I access button and label from here ?
         }
      };
      new Thread(r).start();
   }
}


推荐答案


如何从匿名类的方法中访问实例变量

如果需要,您只需访问它们:

You simply access them if need be:

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println("Button's text is: " + button.getText());
         }
      };
      new Thread(r).start();
   }
}

更重要的是:为什么这不适合你?

More important: Why isn't this working for you?

这篇关于如何从匿名类中访问封闭的类实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆