开发者

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); bre开发者_C百科ak;
            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);


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?


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜