Kyle Wilson
Kyle Wilson

Reputation: 11

Key Listener not working

 public void paint (Graphics g)
{
    bufferGraphics.setColor (Color.black);
    bufferGraphics.clearRect (0, 0, dim.width, dim.width);
    while (input != KeyEvent.VK_SPACE)
    {
        bufferGraphics.fillRect (0, 0, dim.width, dim.height);
    }

    bufferGraphics.drawImage (track, 0, 0, dim.width, dim.height, this);
    bufferGraphics.setFont (new Font ("Calibri", Font.PLAIN, 25));
    bufferGraphics.drawString ("Level: " + level, 30, 30);
    bufferGraphics.drawImage (car, 620, myCarY, 70, 120, this);
    bufferGraphics.drawImage (opponent, 415, oppCarY, 70, 120, this);
    move ();

This is the code as it stands now. When executed, I get a frozen blank window that cannot even be closed.

Upvotes: 1

Views: 201

Answers (1)

Michael
Michael

Reputation: 1239

Your issue is in your if statement.

if(run = false)

will never execute, as assignment returns the value being assigned (e.g. false).

You need to change your = to an ==.

You may also want to change your infinite for loop to a while loop, something like

while(input != KeyEvent.VK_SPACE) {
}

Also make sure that your KeyListener is being added to your class (in ctor)

addKeyListener(new MyKeyListener())

I just tested the code, and it worked.

Upvotes: 1

Related Questions