gpt4 book ai didi

java - 如何在主java中调用Keypress函数

转载 作者:行者123 更新时间:2023-12-02 10:46:17 24 4
gpt4 key购买 nike

所以我的类中只有这个函数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);
}

最佳答案

更新(针对 this comment ):

您将在 keyPressed(KeyEvent e) 方法中收到 NullPointerException ,因为您尚未检查传递的参数是否为 null或在尝试访问e.getKeyCode();之前不这样做。

尝试解析 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);

关于java - 如何在主java中调用Keypress函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52550613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com