I'm using a thread to repaint a JPanel (seeing as repaint()
is thread safe).
我正在使用一个线程来重绘JPanel(看作repaint()是线程安全的)。
Here is the paintComponent method:
这是paintComponent方法:
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Print statement so I know where my program is at.
System.out.println("Repainting world...");
g.drawImage(worldImage, x, y, 6144, 4608, null);
}
I have a thread that starts inside of a KeyListener
whenever a user presses a certain button
每当用户按下某个按钮时,我都有一个在KeyListener内部启动的线程
Run method:
public void run(){
game.repaint();
}
Lastly, here's my calls to the thread that uses the above run method:
最后,这是我对使用上述run方法的线程的调用:
//NOTE: I've tried this without the if statement, made no difference
if(!gameThread.isAlive()){
gameThread.start();
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I'm pretty sure that, with this case (since it's in a KeyListener)
, Thread.join()
stops the EDT
until that run method is executed.
我很确定,在这种情况下(因为它在KeyListener中),Thread.join()会停止EDT,直到执行该run方法。
The problem is, Thread.join
is throwing an InterruptedException
whenever I press the button again, no matter how long I wait. This leads me to believe that somewhere it's getting hung in an area, where the thread will not stop it's execution. I just can't tell where it could potentially be getting hung up.
问题是,无论我多久等待,每当我再次按下按钮时,Thread.join都会抛出InterruptedException。这让我相信它会被某个地方挂在一个区域,线程不会阻止它的执行。我只是无法分辨它可能会被挂断的地方。
1 个解决方案
#1
If I understand this...you're calling repaint() from within your gameThread. Since repaint() executes on the EDT, I think you've blocked it from executing by virtue of the fact that gameThread.join() blocks the EDT (since it's started by the EDT i.e. from within your KeyListener handler).
如果我明白这一点......你在gameThread中调用repaint()。由于repaint()在EDT上执行,我认为你已经阻止它执行,因为gameThread.join()阻止了EDT(因为它是由EDT启动的,即从你的KeyListener处理程序中启动)。
#1
If I understand this...you're calling repaint() from within your gameThread. Since repaint() executes on the EDT, I think you've blocked it from executing by virtue of the fact that gameThread.join() blocks the EDT (since it's started by the EDT i.e. from within your KeyListener handler).
如果我明白这一点......你在gameThread中调用repaint()。由于repaint()在EDT上执行,我认为你已经阻止它执行,因为gameThread.join()阻止了EDT(因为它是由EDT启动的,即从你的KeyListener处理程序中启动)。