Search code examples
netbeansjava-melwuit

the KeyPressed method is not called when I push a game button


I added a gameKeyListener() to my Form for when the up and down Button is presed, but the keyPressed() method is not called. My code:

    Form f = new Form();
         f.addGameKeyListener(Canvas.UP, this);
   f.addGameKeyListener(Canvas.DOWN, this);
          f.show();
}
    public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void actionPerformed(ActionEvent evt) {
       }

   public void keyPressed(int key)
{
   System.out.println ("Pressed");
    switch (key){
        case Canvas.DOWN:
            //code
            System.out.println ("Pressed");
            break;
        case Canvas.UP:
            //code
            System.out.println ("Pressed");
            break;
    }
}

}

Thanks in advance.


Solution

  • When you use addGameKeyListener this fire action event. Try this:

    public void actionPerformed(ActionEvent evt) {
    switch (evt.getKeyEvent()){
            case Canvas.DOWN:
                //code
                System.out.println ("Pressed");
                break;
            case Canvas.UP:
                //code
                System.out.println ("Pressed");
                break;
        }
    

    }