gpt4 book ai didi

java - 即使我不释放按键,也检测到 KeyStroke 释放

转载 作者:行者123 更新时间:2023-11-30 04:10:10 24 4
gpt4 key购买 nike

阅读了一些教程后,我决定从 KeyListeners 切换到 KeyBindings。我想我已经理解它们是如何工作的,但我不明白为什么这个小程序即使我不释放 key 也会检测到 key 释放。编辑:我在 Linux 机器上。

    //KeyBindingsTest.java
import javax.swing.*;
import java.awt.event.*;

public class KeyBindingsTest{
private JFrame w = new JFrame();
private JComponent j = new JPanel();
public KeyBindingsTest(){
w.setSize(400,400);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setVisible(true);
setKeyBindings();
w.add(j);
}

public static void main(String[] args){
new KeyBindingsTest();
}

private void setKeyBindings(){
InputMap im = j.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = j.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "released");

am.put("pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed");
}
});

am.put("released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Released");
}
});
j.setFocusable(true);
j.requestFocusInWindow();
}
}

如果我按住“1”键,我希望程序连续打印:

Pressed 
Pressed
Pressed...

但它打印:

Pressed
Released
Pressed
Released...

我一定错过了一些东西,一些非常简单的东西。

编辑:现在我想出了一个肮脏的解决方法,但我仍然希望有人能解释如何以适当的方式解决这个问题。这是:

            // the beginning of the file should stay the same
private void setKeyBindings(){
InputMap im = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "released");

class MyAction extends AbstractAction{
private String s;
public MyAction(String s){
this.s = s;
}
@Override
public void actionPerformed(ActionEvent e) {
if(s.equals("pressed"))setKeyPressed();
else if(s.equals("released"))tryToSetKeyReleased();
}
}

am.put("pressed", new MyAction("pressed"));
am.put("released", new MyAction("released"));

setFocusable(true);
requestFocusInWindow();


}

public boolean pressed = false;
public void setKeyPressed(){System.out.println("key pressed");pressed =true;}
public void setKeyReleased(){System.out.println("key released");pressed = false;}
public void tryToSetKeyReleased(){
pressed = false;
(new Thread(
new Runnable(){
@Override
public void run() {
try{Thread.sleep(5);}
catch(Exception e){;}
if(pressed==false)setKeyReleased();
}

}
)).start();
}

最佳答案

这与操作系统有关。例如,如果您连续按记事本中的一个字符,它将连续打印该字符。因此,它不断地发送新闻发布信号。

关于java - 即使我不释放按键,也检测到 KeyStroke 释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19810954/

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