不明白为什么e.getKeyCode()无法正常工作

时间:2019-07-04 00:08:33

标签: java keyevent

import java.awt.event.KeyAdapter;

import com.sun.glass.events.KeyEvent;

public class KeyInput extends KeyAdapter {

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println(key);
    }

    public void keyReleased(KeyEvent e) {

    }
}

它说“类型KeyEvent的方法getKeyCode()未定义”,但是当我通过Google搜索它时它在API中吗?

import java.awt.event.KeyAdapter;

import com.sun.glass.events.KeyEvent;

public class KeyInput extends KeyAdapter {

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println(key);
    }

    public void keyReleased(KeyEvent e) {

    }
}

KeyEvent类型的getKeyCode()方法未定义

1 个答案:

答案 0 :(得分:2)

您犯了两个错误。我认为正确的代码应为:

import java.awt.event.KeyAdapter;    
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println(key);
    }

    public void keyReleased(KeyEvent e) {

    }
}

正如Carcigenicate指出的那样,您应该从KeyEvent导入java.awt.event

从根本上讲,如果要覆盖方法,则应使用@Override对其进行标记。这样,如果您(如您所做的那样)不小心重载了该方法,则通过使用其他类型签名,编译器会告诉您。