title: Java, Move Rectangle Back and Forth
body: <p>I'm trying to animate an object to move back and forth between two boundaries. For instance, once the x coordinate of the object reaches 500 it moves in the opposite direction to 200 and then moves back again until it reaches 500 and so on. However, the rectangle will only move to 500 and then stop. Here is a simplified version of my code:</p>
  
  <pre><code>public class Test
  {
  
      public static class Game extends JComponent implements ActionListener
      {
          int width=100;
          int height=100;
          int x=300;
          int y=200;
          Timer timer;
          public Game()
          {
              timer = new Timer(20,this);
              timer.start();
          }
          public void paint(Graphics g)
          {
              g.drawRect(x,y,width,height);
              g.setColor(Color.red);
              g.fillRect(x,y,width,height);
          }
          public void actionPerformed(ActionEvent e)
          {
              if(x&gt;100)
              {
                  x+=5;
              }
              if(x&gt;500)
              {
                  x-=5;
              }
  
              repaint();
          }
      }
      public static void main(String[] args)
      {
          JFrame frame = new JFrame("Test");
          frame.setPreferredSize(new Dimension(800,600));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(new Game());
          frame.pack();
          frame.setVisible(true);
      }
  
  
  }
  </code></pre>