tags:

views:

43

answers:

1

Sorry, for double posting, already posted this question once, but I realized I weren't explicit enough. I still haven't managed to find an answer to my question so I'll try to better describe my problem here:

I have the following classes:

public class Paddle extends JLabel {}
public class Canvas extends JPanel implements Runnable {}

Now, when I start the thread described in Canvas, I want an infinite loop (loops while program is exited). In this loop I've got a DIRECTION variable. When the left arrowkey is pressed I'd like this to be set -1. If right arrow key is pressed I'd like +1 to be it's value. If neither of the above cases is true, it's value should default 0.

I hope I was more explicit this time. If not please tell.

A: 

Well, to get the keystrokes you need to have a class that implements KeyListener

Like this:

public class MyKeyListener implements KeyListener, MouseListener{
   int direction = 0;

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()  == KeyEvent.VK_LEFT) direction = -1;
        else if(e.getKeyCode()  == KeyEvent.VK_RIGHT) direction = 1;
    }

    public void keyReleased(KeyEvent e) {
        direction = 0;
    }
}

Then in your initialization code (for example, in the constructor of your JPanel derived class) you set the key listener to an instance of your MyKeyListener class

   MyKeyListener  mk = new MyKeyListener();
   this.addKeyListener(mk);

In your loop, you just look at the direction feild of mk;

Chad Okere
What exactly do you understand by main code? Main? the JFrame? the JPanel. nothing seems to work. Do i have to set focus to something?
Illes Peter
Probably in the constructor of your Canvas class. You shouldn't need to set focus manually. Try clicking on the canvas. You can add some System.out.println(direction) statements in the keyPressed function to make sure that it's actually getting called.
Chad Okere