Java Key bindings fires both press and release while key is held down

有些话、适合烂在心里 提交于 2019-12-11 03:32:14

问题


So, I made a method that you can pass 2 AbstractAction to, the first one performs the key pressed event and the second performs the key released event.

When the I press and release the UP key both actions get fired off, that is fine. If I press and hold the UP key both actions are still fired off. Why are both being fired? Shouldn't only the Key Pressed one be getting fired?

Main.java:

package sscce;

import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main extends JFrame{

    public Main(){
        this.setSize(500, 400);
        this.setVisible(true);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel room = new Room();
        this.add(room);
    }

    public static void main(String[] args){
        Main run = new Main();
    }

    public class Room extends JPanel{

        public Room(){
            KeyboardEvent keyboard = new KeyboardEvent();
            keyboard.setEvent(this, "UP", new AbstractAction(){
                @Override
                public void actionPerformed(ActionEvent evt){
                    System.out.println("Up Pressed");
                }
            }, new AbstractAction(){
                @Override
                public void actionPerformed(ActionEvent evt){
                    System.out.println("Up Released");
                }
            });
        }
    }

    public class KeyboardEvent extends KeyAdapter{

        public void setEvent(JPanel comp, String key, AbstractAction act, AbstractAction actRelease){
            // Key Pressed
            comp.
                    getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke(key), "do" + key + "Action");
            comp.
                    getActionMap().
                    put("do" + key + "Action", act);

            // Key Relseased
            comp.
                    getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).
                    put(KeyStroke.getKeyStroke("released " + key), "do" + key + "ActionReleased");
            comp.
                    getActionMap().
                    put("do" + key + "ActionReleased", actRelease);
        }
    }
}

来源:https://stackoverflow.com/questions/13882639/java-key-bindings-fires-both-press-and-release-while-key-is-held-down

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