问题
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