import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; class RectanglePanel extends JPanel { public RectanglePanel() { rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.draw(rect); } /** Moves the rectangle and repaints it. The rectangle is moved by multiples of its full width or height. @param dx the number of width units @param dy the number of height units */ public void moveRectangle(int dx, int dy) { rect.translate(dx * RECT_WIDTH, dy * RECT_HEIGHT); repaint(); } private Rectangle rect; private static final int RECT_WIDTH = 20; private static final int RECT_HEIGHT = 30; }