如何在主Java中调用功能Keypress

时间:2018-09-28 07:40:53

标签: java function main keypress keyevent

所以我在课堂上只有这个功能keyPressed(KeyEvent e),而我试图在主要位置调用它,但是它不起作用。我知道我不应该使用null初始化KeyEvent,但我不知道如何调用它

public void  keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    switch(e.getKeyCode()) {

    case KeyEvent.VK_UP:
         break;
    case KeyEvent.VK_DOWN:
         break;
    case KeyEvent.VK_LEFT:
         break;
    case KeyEvent.VK_RIGHT:
         break;
}

public static void main(String args[]){
 Myclass class = new Myclass();
 KeyEvent KeyEvent = null;
 class.keyPressed(KeyEvent);
}

2 个答案:

答案 0 :(得分:1)

更新(针对this comment

您将在NullPointerException方法内得到一个keyPressed(KeyEvent e),因为在尝试访问null之前没有检查传递的参数是否为e.getKeyCode();。 / p>

尝试解析KeyEvent对象

Myclass c = new Myclass();
KeyEvent ke = new KeyEvent(new Component() {}, 0, 0l, 0, KeyEvent.VK_UP);
c.keyPressed(ke);

避免使用关键字作为变量名。试试这个,

Myclass c = new Myclass();
c.keyPressed(null);

答案 1 :(得分:0)

您要向函数发送一个null值作为参数。

所以它肯定会在

崩溃
     int key = e.getKeyCode();

使用NullPointerException,因为enull,因为您不能在getKeyCode()对象上调用null

尝试将有效的KeyEvent对象作为参数传递

例如:

public static void main(String args[]){
   Myclass myclass = new Myclass();
   KeyEvent KeyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1);
   myclass.keyPressed(KeyEvent);
 }

注意:将new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1);替换为代码以找到keyEvent

此外,如果要防止NullPointerException,请在keyPressed函数中进行空检查,如下所示

 public void  keyPressed(KeyEvent e){
            if(e != null){
                int key = e.getKeyCode();

                switch(e.getKeyCode()) {

                case KeyEvent.VK_UP:
                     break;
                case KeyEvent.VK_DOWN:
                     break;
                case KeyEvent.VK_LEFT:
                     break;
                case KeyEvent.VK_RIGHT:
                     break;
            }
        }