如何从匿名类中访问封闭的类实例变量?

如何从匿名类中访问封闭的类实例变量?

问题描述:

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

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?