do something once the key is held and repeat when its released and repressed

二次信任 提交于 2019-12-01 09:08:56

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");

                }

            }

        });

    }

}
Bobulous

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!