user569322
user569322

Reputation:

Java - KeyListener not working

This has been making me want to tear out my hair all day. I'm trying to make it so when I press the right-arrow key, my speed will go to 10. I know that my methods that make my sprite move work, because if I set a value beforehand, it moves across the screen. It's the KeyListener that isn't doing anything:

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Sprite implements KeyListener{
    public Image player = Toolkit.getDefaultToolkit().getImage("player.png");
    int x, y, dx, dy;

    public void doInit(){
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(600, 400);
        window.setLocationRelativeTo(null);
        window.getContentPane().add(new ImageDraw());
        window.setVisible(true);
        window.setIgnoreRepaint(true);
        window.createBufferStrategy(2);
        window.getContentPane().addKeyListener(this);
    }

    public Image getSpriteHandle(){
        return player;
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 10;
         }
    }   //end keyPressed

    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 0;
         }
    }

    public void keyTyped(KeyEvent arg0) {

    } 

    public int moveX(){
        return dx;
    }

}   //end class

Please help me!

Upvotes: 2

Views: 2761

Answers (1)

camickr
camickr

Reputation: 324157

It's the KeyListener that isn't doing anything

You should NOT be using a KeyListener.

Swing was designed to be used with Key Bindings. You can map an Action to a KeyStroke even when a component doesn't have focus.

Upvotes: 5

Related Questions