简体   繁体   English

如何在主Java中调用功能Keypress

[英]how to call function Keypress in the main java

so i've only this function keyPressed(KeyEvent e) in my class and i'm trying to call it in the main but it doesn't work. 所以我在我的课堂上只有这个功能keyPressed(KeyEvent e) ,我试图在主要调用它,但它不起作用。 i know i should not initialize KeyEvent with null but i don't know how to call it 我知道我不应该使用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);
}

Update (for this comment ) : 更新对此评论

You'll get a NullPointerException inside your keyPressed(KeyEvent e) method because you haven't checked whether the passed argument is null or not before trying to access e.getKeyCode(); 您将在keyPressed(KeyEvent e)方法内获得NullPointerException因为在尝试访问e.getKeyCode();之前没有检查传递的参数是否为null e.getKeyCode(); .

Try parsing an KeyEvent object 尝试解析KeyEvent对象

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

Avoid using keywords as variable names. 避免将关键字用作变量名。 Try this, 尝试这个,

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

You are sending a null value as a parameter to the function. 您正在向该函数发送一个null值作为参数。

So It will surely crash at 所以它肯定会在崩溃

     int key = e.getKeyCode();

with a NullPointerException since e is null bacuse you can't call getKeyCode() on a null object 带有NullPointerException因为enull ,所以不能在null对象上调用getKeyCode()

Try passing a valid KeyEvent object as parameter 尝试传递有效的KeyEvent对象作为参数

Eg: 例如:

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

Note: Replace new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1); 注意:替换new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1); with the code to find the keyEvent 用代码查找keyEvent

Also if you want to prevent NullPointerException , put a null check in the keyPressed function as follows 另外,如果您想防止NullPointerException ,请在keyPressed函数中进行null检查,如下所示

 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;
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM