2

因此,我创建了一个可以传递 2 的方法AbstractAction,第一个执行按键事件,第二个执行按键释放事件。

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

主.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);
        }
    }
}
4

0 回答 0