Question

I have public class MainFrame extends JFrame implements ActionListener {

and then later on:

public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
        int x = ball.getX() + 1;
         ball.setX(x);
        }
        }

however it does not seem to respond when I believe it should.

If I add keylistener instead of actionlister I cannot compile which I can't understand. I'm new to java however i'm used to C#

No correct solution

OTHER TIPS

  1. You need to implement java.awt.event.KeyListener not a ActionListener to listen for key events.
  2. You need to register your listener on the element (frame) you want to listen on by invoking addKeyListener(...).

Example:

public class TestFrame extends JFrame implements KeyListener {

    public static void main(String[] args) throws FileNotFoundException {
        TestFrame testFrame = new TestFrame();
        testFrame.setSize(100, 100);
        testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        testFrame.addKeyListener(testFrame);
        testFrame.setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {    }
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println(e);
    }
    @Override
    public void keyReleased(KeyEvent e) {   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top