RectangleComponent3.java.html

  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 RectangleComponent3 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 RectangleComponent3()
 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  
 41     /**
 42        Moves the rectangle by a given amount. 
 43        @param dx the amount to move in the x-direction 
 44        @param dy the amount to move in the y-direction 
 45     */
 46     public void moveRectangleBy(int dx, int dy)
 47     {
 48        box.translate(dx, dy);
 49        repaint();      
 50     }
 51  }