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

前端 未结 2 449
执念已碎
执念已碎 2021-01-14 04:56

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

2条回答
  •  遥遥无期
    2021-01-14 05:02

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

提交回复
热议问题