簡體   English   中英

Java啟動線程問題

[英]Java starting thread issue

這只是我的代碼的一部分,如果你們需要整個代碼,請告訴我。所以我的問題是,這部分是if(shoot) thread.start(); 實際上不起作用,因為我希望它能起作用。按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();
=>  }

啟動您的應用程序后,它創建一個新的JFrame,並將其大小等,創建一個Thread實例,檢查是否shoot是真實的,那是假的所以不會啟動線程。 然后,它在上面提供的位置等待JFrame關閉。 當您單擊shoot ,您的應用程序此時仍在等待,因此它永遠不會檢查shoot是對還是錯。

相反,您可以做的是將上面的代碼移動到您的鍵偵聽方法中。 別忘了也將shoot移到合適的位置。

您可以執行在keyPressed()方法本身中啟動線程的任務,而不是在按下鍵時使變量為true。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM