我有一个在actionPerformed方法中迭代的for循环。基本上,我有一个汽车游戏。我有一个面板,汽车图像在JPanel中从一侧到另一侧。我试图让汽车停在终点线(我正在通过在图像达到某个x值时睡觉)显示比赛结果,离开屏幕并再次比赛。我需要这样做四次,直到我们有一个胜利者。
private class RaceDisplay extends JPanel implements ActionListener{
private Image img1,img2;
private int velX1,velX2;
private int x1,x2;
private Timer tm;
private JTextArea text1 = new JTextArea();
public RaceDisplay(){
tm = new Timer(30,this);
x1=0;
x2=0;
velX1=2;
velX2 =2;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon car1 = new ImageIcon("...");
ImageIcon car2 = new ImageIcon("...");
img1 = car1.getImage();
img2 = car2.getImage();
g.drawImage(img1,x1,100,null);
g.drawImage(img2,x2,200,null);
tm.start();
}
public void actionPerformed(ActionEvent e) {
x1=x1+velX1;
velX2= x2+velX2;
repaint();
for(int count = 0;count<=4;count++){//<-----loop with issues.
if(count == 1){
text1.setText(result());
}
if(x1>=650 && x2>=650){ //does this when both cars reach the line
velX1=0;
velX2=0;
try {
Thread.sleep(2500);
} catch (InterruptedException ex) {
Logger.getLogger(Display.class.getName()).log(Level.SEVERE, null, ex);
}
x1=0;
x2=0;
repaint();
velX1= x1+velX1;
velX2= x2+velX2;
}
}
repaint();
}
我创建了for循环,它应该在if语句到达最后一个计数器时检查它是否显示获胜者(代码中获胜者的方法)。我期待图像从一侧传到四次并显示四次结果。 但是如果我将if(counter == 1)设置为(counter == 0),它只会显示任何内容。 有人可以帮忙吗? 感谢。
答案 0 :(得分:1)
tm.start();
,这只是在寻找麻烦。绘画可能由于多种原因而发生,其中许多原因是您无法控制或了解paintComponent
。这不会阻止Thread.sleep
,但会阻止EDT处理事件队列,其中包括重绘事件和计时器事件...... 相反,一旦您检测到汽车已经通过终点线,您可以停止更新该汽车的位置和/或停止Timer
Timer
仔细查看Concurrency in Swing了解更多详情