      1  import java.awt.Graphics;

      2  import java.awt.Graphics2D;

      3  import java.awt.Rectangle;

      4  import javax.swing.JComponent;

      5

      6  /**

      7     This component displays a rectangle that can be moved.

      8  */

      9  public class RectangleComponent extends JComponent

     10  {

     11     private static final int BOX_X = 100;

     12     private static final int BOX_Y = 100;

     13     private static final int BOX_WIDTH = 20;

     14     private static final int BOX_HEIGHT = 30;

     15

     16     private Rectangle box;

     17

     18     public RectangleComponent()

     19     {

     20        // The rectangle that the paintComponent method draws

     21        box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);

     22     }

     23

     24     public void paintComponent(Graphics g)

     25     {

     26        Graphics2D g2 = (Graphics2D) g;

     27

     28        g2.draw(box);

     29     }

     30

     31     /**

     32        Moves the rectangle by a given amount.

     33        @param x the amount to move in the x-direction

     34        @param y the amount to move in the y-direction

     35     */

     36     public void moveBy(int dx, int dy)

     37     {

     38        box.translate(dx, dy);

     39        repaint();

     40     }

     41  }