gpt4 book ai didi

Java key 适配器

转载 作者:行者123 更新时间:2023-12-01 16:09:59 30 4
gpt4 key购买 nike

我有点不熟悉Java KeyAdapter有效,并且使用 KeyAdapter 使用以下代码得到了意想不到的结果。当按下一个键而另一个键已按下时,就会出现此问题,无论 isKeyPressed() 是否有效。被调用。

注意:我知道这是很多代码,对此我深表歉意。我尽了最大努力来隔离它,我认为它主要存在于 keyHandler 中的评论周围。下面的方法(如何 keyHandler() 将当前按下的键放入 keysHeld )。希望详尽的评论对您有所帮助。

key 处理程序:

ArrayList keysHeld = new ArrayList<KeyEvent>();

private void keyHandler()
{
KeyAdapter keyListnr = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();

int index = 0;
boolean found = false;
while(!found && index<keysHeld.size()) //While not already found, and end of ArrayList not reached
{
System.out.print("errorCheck: keysHeld: "+keysHeld+", "+(Object)keyCode+" "); //PRINT
if(keysHeld.get(index) == (Object)keyCode)
{
System.out.println("found"); //PRINT
found = true; //This key is already recognized as held
}
else
{
System.out.println("not found"); //PRINT
//This key is not recognized as held
}
}
if(!found) //If key must be added to keysHeld
{
keysHeld.add(keyCode); //Add to list of held keys
}
System.out.println(keysHeld.toString()); //PRINT ArrayList of all held keys
} //end of keyPressed


public void keyReleased(KeyEvent e) //similar in concept to keyPressed
{
int keyCode = e.getKeyCode();

int index = 0;
boolean found = false;
while(!found && index < keysHeld.size())
{
if(keysHeld.get(index) == (Object)keyCode)
{
keysHeld.remove(index); //remove key from keysHeld
found = true;
}
else
{
index++;
}
}
System.out.println(keysHeld.toString()); //PRINT ArrayList of all held keys
} //end of keyReleased
};
addKeyListener( keyListnr );
}

isKeyHeld:

public boolean isKeyHeld(int e)
{
int keyCode = e;
Object key = (Object)keyCode;

if(!keysHeld.isEmpty())
{
int index = 0;
while(index<keysHeld.size())
{
if(keysHeld.get(index) == key)
{
return true;
}
index++;
}
}
return false;
}

控制台输出:(按住左箭头[37],然后按下右箭头[39])

[37]
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
...

最佳答案

几点:

  • 您没有填写 keysHeld包含 KeyEvent 实例的数组,但使用 autoBoxed Integer源自 int 的对象键码。
  • 您需要增加 index如果你想摆脱 while 变量循环输入keyPressed
  • 您不应该使用 ==比较两者Objects在你的while循环

您可以使用如下内容进行测试:

    if(keysHeld.get(index++).equals(new Integer(keyCode))

关于Java key 适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1633606/

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