user3466846
user3466846

Reputation: 11

Trouble with KeyListener in animation

I am trying to make a simple animation using ActionListener and KeyListener that will take in keyboard inputs, namely the arrow keys. The problem is the program is not compiling with KeyListener. Can someone please shed some light on why and possibly provide help with a solution. Thanks!

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Planegame extends JPanel implements ActionListener, KeyListener
{   //^^ this line is giving me trouble^^^^

Timer tim = new Timer(20, this);
int x = 0, y = 0, velX = 0, velY = 0;
public Planegame()
{
    tim.start();         //this will start my animation
    addKeyListener(this);   // will activate the keylistner to watch key press   
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);  //disables shift and tab key
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.GREEN);
    g.fillOval(x, y, 10, 10);
}

public void actionPerformed(ActionEvent e)     
{
    x = x + 10;  //velX 
    y = y + velY;
    repaint();
}

public void keyPressed(KeyEvent e)
{
    if(e.getKeyCode()==38) 
    {
        velY = 1;
    }
    if(e.getKeyCode()==40)
    {
        velY = -1;
    }
    if (e.getKeyCode()==32)   //booster power
    {
        velX = 3;
    }
}

public void keyTyped(KeyEvent e) {}

public void keyReleased(keyEvent e) {}

public static void main(String[] args)
{
    PlaneGame zed = new PlaneGame();
    JFrame k = new JFrame();
    k.setTitle("game");
    k.setSize(600,400);
    k.setVisible(true);
    k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    k.add(zed);
}
}

Upvotes: 1

Views: 487

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347214

You have a typo in the declaration of keyReleased method...

public void keyReleased(keyEvent e) {

Remember, Java is case sensitive, it should be...

public void keyReleased(KeyEvent e) {

Note the uppercase K in KeyEvent

You wish to consider using the @Override annotation on methods that you think you are overriding, this will alert you when you've made a mistake of some kind, for example

@Override
public void keyReleased(KeyEvent e) {

There's also no reason why paintComponent should be public, you never want some one outside of your component to call it

As always, I'd advise using key bindings over KeyListener as they provide better control over the level of focus your component needs to be able to trigger a key event

Upvotes: 5

Related Questions