rowanv
rowanv

Reputation: 1

Trouble implementing KeyListener

I'm making a simple game and I was just trying to implement a KeyListener. It tells me that I must implement the abstract method KeyReleased but I already implemented the three KeyListener methods (I think). Any help would be appreciated. Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class mainGame extends JFrame implements KeyListener{
JPanel pane4=new JPanel();

public static void main (String [] args){
    new mainGame();
}
public mainGame(){
    super ("game");
    setSize(800,600);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setResizable(false);
    setLocationRelativeTo(null);
    pane4.addKeyListener(this);
    add(pane4);
    setVisible(true);
}
public void KeyTyped(KeyEvent e){
    //not using this method
}
public void KeyPressed(KeyEvent e){

    int keyID=e.getKeyCode();

    if (keyID==e.VK_ESCAPE){
        dispose();
        menu.main(null);
    }
    else if (keyID==e.VK_KP_RIGHT){

    }
    else if (keyID==e.VK_KP_RIGHT){

    }


}
public void KeyReleased(KeyEvent e){
    //not using this method
}

}

Upvotes: 0

Views: 46

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Capitalization matters. It's keyReleased not KeyReleased. Voting to close as a typographical error.

To prevent future similar problems, always use the @Override annotation before any methods that you think should override a super's method. Doing this will have the compiler warn you of any errors. e.g.,

@Override
public void KeyReleased(KeyEvent e){
    //
}

This code above will cause a compiler error and clue you in that you need to fix something in the method signature to make it fit.

Other unrelated points:

  • It's best to avoid having your GUI classes implement the listener interfaces, since that is giving the class too much responsibility. Better to either use anonymous inner classes (look these up if you're not familiar with them), or private inner classes or stand alone classes.
  • You're likely better off using key bindings and not KeyListeners to react to Swing non text component key presses.

Upvotes: 2

Related Questions