Matt Martin
Matt Martin

Reputation: 855

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();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!

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;
}

Upvotes: 2

Views: 115

Answers (2)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Instead of making variable true when a key is pressed, what you can do is perform the task of starting the thread within the keyPressed() method itself.

Upvotes: 2

mostruash
mostruash

Reputation: 4189

    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. Afterwards it waits at the point provided above for JFrame to be closed. When you click shoot, your application is still waiting at that point so it never checks if shoot is true or false.

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.

Upvotes: 3

Related Questions