Why can't I access outer class from inner Thread class in Java?

I have these class and its nested classes (please go to the relevant line):

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Client {
  private static final int FRAME_WIDTH = 500, FRAME_HEIGHT = 500;

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new ClientPanel());
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        frame.setVisible(true);
      }
    });
  }

  @SuppressWarnings("serial")
  private static class ClientPanel extends JPanel {
    JTextArea textArea;
    JTextField textField;
    JButton goButton;

    private ClientPanel() {
      setLayout(new BorderLayout());

      textArea = new JTextArea();
      add(textArea, BorderLayout.NORTH);

      textField = new JTextField();
      add(textField, BorderLayout.CENTER);

      goButton = new JButton("Go");
      add(goButton, BorderLayout.PAGE_END);
      goButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          textArea.append("Go button pressed. Text in field: "
              + textField.getText() + "\n ");
        }
      });
    }

    private static class GetBinaryThread extends Thread {
      private String data;

      public GetBinaryThread(String data) {
          this.data = data;
      }

      public void run() {
        try {
          ClientPanel.this.textArea.append(", recieved" + data);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
}

The compiler gives me an error on line:

ClientPanel.this.textArea.append(", recieved" + data);

No enclosing instance of the type Client.ClientPanel is accessible in scope

How am I able to access the JTextArea of the outer class?

Jon Skeet
people
quotationmark

Your nested class is a static nested class:

private static class GetBinaryThread extends Thread

Therefore it doesn't have an enclosing instance.

Get rid of static and then it'll be an inner class, with a reference to an instance of ClientPanel. Note that when you create an instance of GetBinaryThread (which you don't in the code you've shown) you'll need to have a ClientPanel reference to implicitly pass to the constructor as context.

people

See more on this question at Stackoverflow