简体   繁体   中英

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. i know i should not initialize KeyEvent with null but i don't know how to call it

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(); .

Try parsing an KeyEvent object

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.

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

Try passing a valid KeyEvent object as parameter

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); with the code to find the keyEvent

Also if you want to prevent NullPointerException , put a null check in the keyPressed function as follows

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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