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 RectangleComponent2 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 RectangleComponent2()
 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        g2.draw(box);
 28     }
 29  
 30     /**
 31        Moves the rectangle to the given location.
 32        @param x the x-position of the new location
 33        @param y the y-position of the new location
 34     */
 35     public void moveRectangleTo(int x, int y)
 36     {
 37        box.setLocation(x, y);
 38        repaint();      
 39     }
 40  }