title: Java Arrow key KeyLIstener logic
body: <p>So I have am trying to make a keyListener for the arrow keys that responds to the arrow keys, and can handle multiple keys at once. I am trying to put the keys pressed into an ArrayList, and then handle them in my repaint() method. However, I have a problem. I am unsure where to add the keys, and where to remove them. I am not looking so much for a code solution as much as the logic that should go behind this. </p>
  
  <pre><code>    //graham
  
  import java.awt.Color;
  import java.awt.Dimension;
  import java.awt.Graphics;
  import java.awt.event.KeyEvent;
  import java.awt.event.KeyListener; 
  import java.util.ArrayList;
  
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  class Arrows extends JPanel implements KeyListener {
  private int c = 0;
  private int x = 250;
  private int y = 250;
  private static ArrayList&lt;Integer&gt; keys = new ArrayList&lt;Integer&gt;(); 
  
  
  public Arrows() {
      this.setPreferredSize(new Dimension(500, 500));
      addKeyListener(this);
  }
  
  public void addNotify() {
      super.addNotify();
      requestFocus();
  }
  
  public void paintComponent(Graphics g) {
  
      //*********
      //need to update to make so can press (and hold) multiple different keys at once
      //*********
  
      g.setColor(Color.WHITE);
      g.fillRect(x, y , 20, 20);
      for(int i = 0; i &lt; keys.size(); i++){ //********&gt; only want to handle one at a time
          //handle each key
          c = keys.get(i);
          switch(c){
          case 37: 
              //left arrow 
              x -= 10;
              keys.remove(i);
              break;
          case 38:
              // up arrow
              y -= 10;
              keys.remove(i);
              break;
          case 39:
              //right arrow
              x += 10;
              keys.remove(i);
              break;
          case 40:
              //down arrow
              y += 10;
              keys.remove(i);
              break;
          }
      }
      g.setColor(Color.BLUE);
      g.fillRect(x, y, 20, 20);
  }
  
  
  
  public void keyPressed(KeyEvent e) { 
      //******
      //need to create a list of keys pressed, then process them in the repaint. Later delete them after pressed
      //******
      keys.add(e.getKeyCode());
      //repaint();
  }
  public void keyReleased(KeyEvent e) { 
      //****
      //here need to repaint --- need to correct to do something proper later --- due to holding down a key teleports..
      //****
      repaint();
  }
  public void keyTyped(KeyEvent e) {
  }
  
  public static void main(String[] s) {
      JFrame f = new JFrame();
      f.getContentPane().add(new Arrows());
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.pack();
      f.setVisible(true);
  
      //need to null out keys
      keys.add(65);
  }
  }
  </code></pre>