按住键时,Java Key绑定会触发按下和释放

时间:2012-12-14 16:29:00

标签: java swing key-bindings

所以,我做了一个方法,你可以传递2 AbstractAction,第一个执行按键事件,第二个执行键释放事件。

当我按下并释放 UP 键时,两个动作都会被触发,这很好。如果我按住 UP 键,两个动作仍会被触发。为什么两人都被解雇?是不是只有被按下的按键被解雇了?

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

0 个答案:

没有答案