title: Moving Shapes With KeyListener In Java
body: <p>I'm trying to write a program that allows a user to move a shape with arrow keys and change its color with the enter key.  I wasn't taught anything about GUIs or event-based programming, so this is my first experience with any of that.  I think I understand the basics of it, but I'm having trouble just finishing the syntax to make everything run.  The tutorials I find online use timers, which I'm not using.  Here's my current code:</p>
  
  <pre><code>import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
  
  public class Lab15Panel extends JPanel
  {
      Color[] colors = new Color[]{Color.blue, Color.green, Color.red, Color.orange, Color.yellow};
      int initialX = 90;
      int initialY = 80;
  
  public void paintComponent(Graphics g)
  {
      super.paintComponent(g);
  
      g.setColor(colors[0]);
  
  
      g.fillRect(initialX, initialY, 100, 100);
  
  
      Lab15Key listen = new Lab15Key();
  
  }
  
  private class Lab15Key implements KeyListener
  {
      @Override
      public void keyTyped(KeyEvent event)
      {
          if (event.getKeyChar() == KeyEvent.VK_LEFT)
          {
              initialX++;
          }
      }
  
      @Override
      public void keyReleased(KeyEvent event)
      {}
  
      @Override
      public void keyPressed(KeyEvent event)
      {}
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I make my frame in a different class.  Right now I'm unsure of two things:
  1. How do I use addKeyListener with the filled shape?  Is there a way to refer to the filled shape?
  2. Is my idea of "moving" the shape correct?  That is, creating variables outside of the methods for the position of the shape and then using my KeyEvents to change those numbers?  Or will the shape not be moved in this case? (Note I've only written the code for the up key event.)</p>
  
  <p>Any help you can give me would be appreciated.  I'm definitely a Java novice, and I'm just trying to understand these basic concepts but the resources I have aren't helping.</p>