user328898
user328898

Reputation:

I can't get KeyEvent listener to work

Ok, first off. If I do System.out.println(e); that does print when I push the key. However I can not for the life of me figure out how to store this into an int. My IDE gives me no errors if I do int pressed = e.KEY_PRESSED(); or int pressed = e.getKeyCode(); but if I try to print pressed nothing happens.

I've been trying to get this to work for hours and Googling KeyEvent handlers and the Javadocs seem to be of little help to me on this.

public void keyPressed(KeyEvent e) {
    pressed = e.getKeyCode();
    System.out.println(pressed);

}

    do{
        time = System.currentTimeMillis();
        do{
            if(pressed == 37||pressed==38||pressed==39||pressed==40){
                lastvalid=pressed;
            }
        }
        while(System.currentTimeMillis() < time + speed);

        switch(lastvalid){
            case 37: catarloc.set(0, (Integer)catarloc.get(0)-1); break;
            case 38: catarloc.set(1, (Integer)catarloc.get(1)-1); break;
            case 39: catarloc.set(0, (Integer)catarloc.get(0)+1); break;
            case 40: catarloc.set(1, (Integer)catarloc.get(1)+1); break;
        }

        if(Math.random() > .95 || apples < 1){
            applearray[(int)(Math.random()*100/2.8)][(int)(Math.random()*100/4)] = true;
            apples++;
        }
        score+=catarloc.size()-1;
        label.setText("Score     "+ score);
        mainWindow.repaint();
    }
    while(win == false || lose == false);

Upvotes: 2

Views: 793

Answers (2)

Grodriguez
Grodriguez

Reputation: 21995

Depending on the type of event:

  • keyEvent.getKeyChar() gives you the character associated with the key, but only for KEY_TYPED events. Otherwise it returns CHAR_UNDEFINED
  • keyEvent.getKeyCode() gives you the virtual key code, but only for KEY_PRESSED and KEY_RELEASED events. Otherwise it returns VK_UNDEFINED.

Upvotes: 1

Andy
Andy

Reputation: 5218

What about keyEvent.getKeyCode()? It returns an int. KEY_PRESSED is a static final int member on KeyEvent and represents an event when a key is pressed down, not the actual key code.

Update: (Whoops) I see that you already tried getKeyCode. What happens if you print getKeyLocation or getKeyChar?

Upvotes: 1

Related Questions