I am trying to have a thread to listen to keys - which is a different class to where the JPanel
is created. Below is the class where the JPanel
is.
public class Game extends JPanel {
public static final int WIDTH = 600,
HEIGHT = 650;
private static boolean running;
private BufferedImage image;
private Graphics2D g;
public String str;
private static Thread MyThread;
public Game() {
super();
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
}
public void addNotify(){
super.addNotify();
MyThread myThread = new MyThread(this);
if(myThread == null){
myThread = new Thread(myThread);
myThread.start();
}
}
public void run() {
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
while(running){
update();
render();
draw();
System.out.println(str);
}
stop();
}
private void update(){ }
private synchronized void render(){
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private synchronized void draw(){
Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
public void start(){
if(running) return;
running = true;
run();
}
private void stop() {
if(!running) return;
running = false;
try{
myThread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
Below is the code where the thread that listens to the Game
class:
public class MyThread implements Runnable, KeyListener{
private static Game game;
private static boolean left, right;
public MyThread(Game game) {
this.game = game;
}
@Override
public void run() {
game.addKeyListener(this);
if(left){game.str = "left";}
if(right){game.str = "right";}
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){left = true;}
if(key == KeyEvent.VK_RIGHT){right = true;}
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){left = false;}
if(key == KeyEvent.VK_RIGHT){right = false;}
}
@Override
public void keyTyped(KeyEvent e) {
}
}
Currently when I run the code, it only prints out null
even when I try to click left and right arrow keys. I tried inserting game.str = "string";
in the run()
method and the console prints out string
, so the thread works. I think the problem is that MyThread
is not listening to the JPanel
. Can you please tell me how do I fix this -- having a separate thread to listen to the Game
class?
PS. game.addKeyListener(this)
is in the run()
method of the MyThread
class.