user2080377
user2080377

Reputation: 1

Cannot find method in inner class

My code:

 public class MyPanel extends JPanel {
   private Thread spawnRnn = new Thread(new SpawnRnn());

   public MyPanel() {
     spawnRnn.start();
   }

   public class SpawnRnn implements Runnable {
     public void loadData() {}
     public void run() {}
   }
   public class MainRnn implements Runnable {
     public void run() {
       spawnRnn.loadData(); //<--cannot find symbol. symbol: method loadData()
                            //location: variable spawnRnn of type Thread
     }
   }
}

I pointed place where error occurs. What is the reason and how to solve it?

Upvotes: 0

Views: 131

Answers (3)

madlymad
madlymad

Reputation: 6530

The problem is that spawnRnn is of type Thread not SpawnRnn.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500615

As the compiler says, spawnRnn is of type Thread, not of type SpawnRnn... it doesn't have a loadData method. You probably want something like this:

public class MyPanel extends JPanel {
   private final Thread thread;
   private final SpawnRnn spawnRnn;

   public MyPanel() {
      spawnRnn = new SpawnRnn();
      thread = new Thread(spawnRnn);
      thread.start();
   }

   public class SpawnRnn implements Runnable {
     public void loadData() {}
     public void run() {}
   }

   public class MainRnn implements Runnable {
     public void run() {
       spawnRnn.loadData();
     }
   }
}

This way you have access to the instance of SpawnRnn which was used to create the thread. It's unclear whether you actually need the thread variable, or whether you could just use a local variable in the constructor.

(Also I've made the variables final on the grounds that when you can do so, it makes the code easier to reason about.)

Upvotes: 2

Alexandre Vin&#231;on
Alexandre Vin&#231;on

Reputation: 954

Well, that's an easy one. "spawnRnn" is of type "Thread", not "SpawnRnn"

Upvotes: 2

Related Questions