Search code examples
javakeyevent

How to run a method which has "KeyEvent e" as it's parameter?


Hi Devs I have a problem that how should I call it. If I write "null" in the parenthesis, it gives error that e is null. My code is below for reference.

private void myMethod(KeyEvent e){
    if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
        System.exit(0);
    }else if(e.getKeyCode() == e.KeyEvent.VK_SPACE){
        label.setText("This is aa example");
    }
}

public static void main(String[] args){
    Main m = new Main();
    m.myMethod(??); //What should I enter in the parenthesis?
}

Solution

  • To work with actions or KeyEvents, you need to attach a Listener to a component. you don't have a component that'll take one, and you don't have a Listener