gpt4 book ai didi

java - 按住键后做某事并在释放和按下时重复

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:32:49 26 4
gpt4 key购买 nike

我需要检查用户何时按下并释放键。如果有 key 在,我会做一次。

我使用击键来获取我想要关联操作的按钮。我还使用了一个信号量来解决这个问题,但它看起来很疯狂

我的代码:`

InputMap inputMap = jPanel1.getInputMap();
KeyStroke keyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false);
KeyStroke keyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true);
//------------------------------------------
jPanel1.getActionMap().put("_1000Press", _1000Press);
inputMap.put(keyPressed, "_1000Press");
jPanel1.getActionMap().put("_1000Release", _1000Release);
inputMap.put(keyReleased, "_1000Release");
public Action _1000Press = new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {
if(!one){
// do some thing
one = true;
System.out.println(one);
}
}
};
public Action _1000Release = new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {
one = false;
System.out.println(one);
}
};

`

当我按住“1”键时,它会打印: 错误的 真的 错误的 真的 错误的 是的

提前致谢。

最佳答案

这对我来说很好

InputMap im = getInputMap();
ActionMap am = getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "Press");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "Release");

am.put("Press", new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {

if (!pressed) {

pressed = true;
System.out.println("press");

}

}

});

am.put("Release", new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {

if (pressed) {

pressed = false;
System.out.println("release");

}

}

});

只是为了确保我这样做了

am.put("Release", new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {

pressed = false;
System.out.println("release");

}

});

它仍然有效

当我按住 1 时打印 press,然后当我释放键时打印 release。那是我得到的唯一输出

已更新完整代码

public class TestPane extends JPanel {

private boolean pressed;

public TestPane() {

InputMap im = getInputMap();
ActionMap am = getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), "Press");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true), "Release");

am.put("Press", new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {

if (!pressed) {

pressed = true;
System.out.println("press");

}

}

});

am.put("Release", new AbstractAction() {

@Override
public void actionPerformed(ActionEvent e) {

if (pressed) {

pressed = false;
System.out.println("release");

}

}

});

}

}

关于java - 按住键后做某事并在释放和按下时重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917377/

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