1

So I can't use 2 keys at the same time and I'd like that to be able to happen.

My code is here:

https://pastebin.com/DQcS9DVi

if you try and move both of them at the same time, only one will move or none will move. I think it has something to do with this code here:

public KeyBidings(){
        Action upAction = new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                y2 -=10;
            }
        };
    Action downAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
        y2 +=10;
        }
        
    };
        Action wAction = new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                y -=10;
            }
        };
    Action sAction = new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
        y +=10;
        }
        
    };
    drawPanel.repaint();
            InputMap inputMap = drawPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
            ActionMap actionMap = drawPanel.getActionMap();
 
        inputMap.put(KeyStroke.getKeyStroke("DOWN"), "downAction");
        actionMap.put("downAction", downAction);
        inputMap.put(KeyStroke.getKeyStroke("UP"), "upAction");
        actionMap.put("upAction", upAction);
 
        inputMap.put(KeyStroke.getKeyStroke("S"), "sAction");
        actionMap.put("sAction", sAction);
        inputMap.put(KeyStroke.getKeyStroke("W"), "wAction");
        actionMap.put("wAction", wAction);
camickr
  • 321,443
  • 19
  • 166
  • 288
Liambro64
  • 19
  • 3
  • What causes the `DrawPanel` to update when a key binding is triggered? – MadProgrammer Nov 25 '20 at 22:51
  • @MadProgrammer look at line 118 of the pastebin paste – Liambro64 Nov 25 '20 at 22:58
  • 3
    DO NOT call `repaint` inside your `paint` method - this is going to cause you no end of issues. Use a Swing `Timer` instead. This is a relatively common issue. Instead of updating the state of the value inside the `Action` for the key, use a state value to indicate if it's pressed or not and use the `Timer` to update model based on this state - for [example](https://stackoverflow.com/questions/20672834/how-can-i-make-multiple-key-bindings-work-at-the-same-time/20672914#20672914) – MadProgrammer Nov 25 '20 at 22:58
  • An event is only generated for one key at a time. So you need to track all keys pressed (in a Map or something) and then removed the keys when they are released. Your motion will then be based on all the keys in the Map. Check out [Motion Using the Keyboard](http://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/). The `KeyboardAnimation.java` code contains a complete working example that demonstrates one way to do this. – camickr Nov 26 '20 at 00:06

0 Answers0