I need to check when the user presses on a key and releases it. If a key is held in, I will do something once.
I used the keystroke to get the button I want to relat
I don't believe you can achieve what you need in Linux, because the operating system continually issues press/release signals to the JVM.
See
This works fine for me
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");
}
}
});
Just to make sure I did this
am.put("Release", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
pressed = false;
System.out.println("release");
}
});
And it still worked
Printed press
when I pressed and held 1 and then printed release
when I released the key. That was the only output I got
UPDATED with Full Code
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");
}
}
});
}
}