简体   繁体   English

Java启动线程问题

[英]Java starting thread issue

Here's just part of my code, if you guys would need whole code, let me know.So my issue is, that this part if(shoot) thread.start(); 这只是我的代码的一部分,如果你们需要整个代码,请告诉我。所以我的问题是,这部分是if(shoot) thread.start(); actually doesn't work as I'd like it to work.Using KeyListener boolean variable shoot becomes true after pressing space key.If I use just thread.start() everything works fine, but I don't want to start thread on program launch, but after pressing space button(after variable shoot becomes true).Thank you for suggenstions! 实际上不起作用,因为我希望它能起作用。按Key键后,使用KeyListener布尔变量hoot变为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();
=>  }

After you start your application, it creates a new JFrame, sets its size etc., creates a Thread instance, checks if shoot is true, it is false thus does not start the thread. 启动您的应用程序后,它创建一个新的JFrame,并将其大小等,创建一个Thread实例,检查是否shoot是真实的,那是假的所以不会启动线程。 Afterwards it waits at the point provided above for JFrame to be closed. 然后,它在上面提供的位置等待JFrame关闭。 When you click shoot , your application is still waiting at that point so it never checks if shoot is true or false. 当您单击shoot ,您的应用程序此时仍在等待,因此它永远不会检查shoot是对还是错。

What you can do instead would be moving the code above into your key listening method. 相反,您可以做的是将上面的代码移动到您的键侦听方法中。 Don't forget to move shoot into appropriate place too. 别忘了也将shoot移到合适的位置。

您可以执行在keyPressed()方法本身中启动线程的任务,而不是在按下键时使变量为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM