title: How to use KeyListener with JFrame?
body: <p>So, I was trying to make a rectangle move with a <code>KeyEvent</code> (<code>KeyListener</code>) and whenever I try to hit the key, the rectangle doesn't move.</p>
  
  <p>The rectangle is drawn, but whenever I hit the <code>left</code> and <code>right</code> keys, nothing happens.
  I have two classes, one is my main class with the keyEvents and the frame and the other, draws the rectangle and holds the function to move the rectangle.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>import java.awt.event.KeyEvent;
  import java.awt.event.KeyListener;
  
  import javax.swing.JFrame;
  
  
  public class mainFrame extends JFrame implements KeyListener{
  
  mainDraw Draw = new mainDraw();
  
  public void keyPressed(KeyEvent e) {
  
      int key = e.getKeyCode();
  
      if(key == KeyEvent.VK_D){
  
          Draw.moveRight();
      }
  }
  
  public void keyReleased(KeyEvent e) {
  
  
  }
  public void keyTyped(KeyEvent e) {}
  
  public mainFrame()
  {
      addKeyListener(this);
      setFocusable(true);
      setFocusTraversalKeysEnabled(false);
  }
  
  public static void main(String[] args) {
  
      mainFrame M1 = new mainFrame();
  
      mainDraw Draw = new mainDraw();
  
      JFrame frame = new JFrame("Square Move Practice");
  
  
      //frame
      frame.setVisible(true);
      frame.setResizable(false);
      frame.setSize(600, 600);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(Draw);
  
  }
  }
  </code></pre>
  
  <p>And now the second class:</p>
  
  <pre><code>import java.awt.Color;
  import java.awt.Graphics;
  
  import javax.swing.JComponent;
  
  public class mainDraw extends JComponent{
  
  public int x = 50;
  public int y = 50;
  
  public void paint(Graphics g){
  
      g.drawRect(x, y, 50, 50);
      g.fillRect(x, y, 50, 50);
      g.setColor(Color.BLACK);
  }
  
  public void moveRight()
  {
      x = x + 5;
      y = y + 0;
      repaint();
  }
  
  }
  </code></pre>
  
  <p>Please tell me how I can move the rectangle.
  Thanks in advance!</p>