0

Hi I got an error that is about the gameThread variable in my java code is says: "Exception in thread "Thread-0" java.lang.Error: Unresolved compilation problem: gameThread cannot be resolved to a variable"

any ideas thanks for the help

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;


public class GamePanel extends JPanel implements Runnable{

    public void startGameThread(){
        Thread gameThread = new Thread(this);
        gameThread.start();
    }
    @Override
    public void run(){
        while(gameThread != null){ 
            
            
        }
    }
    
}
0

1 Answer 1

0

The problem is that gameThread is defined in function scope - that implies two things:

  1. It is not visible outisde of the scope of this function - rest of the GamePanel class does not know anything about its existence.

  2. It gets destroyed as soon as your function startGameThread() returns:

public void startGameThread() {
        Thread gameThread = new Thread(this);
        gameThread.start();
    } // end of function, gameThread is no longer alive

What you want is to make the thread variable a non-static class member:

public class GamePanel extends JPanel implements Runnable{

    public Thread gameThread;

    public void startGameThread() {
        gameThread = new Thread(this);
        gameThread.start();
    }
    @Override
    public void run(){
        while(gameThread != null) { 
            
            
        }
    }
}

Since startGameThread() is marked public, it is probably wise to check for scenarios where it gets called multiple times:

public void startGameThread() {
        if(gameThread == null) {
            gameThread = new Thread(this);
            gameThread.start();
        }
    }

Unless you already have control over this - then it is fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Using a prefix to identify members is not an accepted practice in Java coding standards. Using those may be confusing to beginners.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.