这只是我的代码的一部分,如果你们需要完整的代码,请告诉我。所以我的问题是,这部分 if(shoot) thread.start();
实际上并不'不能按我希望的方式工作。使用 KeyListener boolean 变量在按空格键后变为 true。如果我只使用 thread.start()
一切正常,但我不想在程序启动时启动线程,但在按空格键后(变量射击变为真后)。谢谢您的建议!
public void paintComponent(Graphics g){
super.paintComponent(g);
i=new ImageIcon("C:\\Users\\Jakub\\Desktop\\pm.gif");
pacman=i.getImage();
g.drawImage(pacman,x,y,this);
if(shoot){
g.drawOval(newX+20,y+10,10,10);
}
if(repaint)
repaint();
}
public static void main(String args[]){
Buffer z= new Buffer();
z.setBackground(Color.cyan);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
thread=new Thread(){
public void run(){
try{
for (int i=0;i<=20;i++){
newX=newX+i;
repaint=true;
Thread.sleep(100);
}
}catch(InterruptedException v){System.out.println(v);}
}
};
if(shoot)
thread.start();
}
if(e.getKeyCode()==KeyEvent.VK_SPACE){
shoot=true;
}
最佳答案
if(shoot)
thread.start();
=> }
启动应用程序后,它会创建一个新的 JFrame,设置其大小等,创建一个 Thread
实例,检查 shoot
是否为 true,因此为 false不启动线程。然后,它在上面提供的点等待 JFrame 关闭。当您单击 shoot
时,您的应用程序此时仍在等待,因此它永远不会检查 shoot
是 true 还是 false。
您可以做的是将上面的代码移动到您的关键监听方法中。不要忘记将射击
移动到适当的位置。
关于Java启动线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17762548/