// RectanglePanel.java // From Cay Horstmann's Computing Concepts with Java 2 Essentials. // Adapted by Scot Drysdale. Further changes by THC. // The RectanglePanel class is really our "canvas" for displaying the rectangle. import java.awt.*; import javax.swing.*; public class RectanglePanel extends JPanel { private static final long serialVersionUID = 1L; private Rect theRect; private static final int RECT_WIDTH = 20; private static final int RECT_HEIGHT = 30; // To construct a RectanglePanel, we also construct a Rect that it will display. public RectanglePanel() { theRect = new Rect(0, 0, RECT_WIDTH, RECT_HEIGHT, Color.red); setBackground(Color.yellow); } // To draw on a JPanel, we DON'T call paint. Instead, we call paintComponent. // paintComponent should ALWAYS have as its first line a call to // super.paintComponent. public void paintComponent(Graphics page) { super.paintComponent(page); theRect.fill(page); // Draw a grid. int panelWidth = getWidth(); int panelHeight = getHeight(); page.setColor(Color.lightGray); // Draw vertical grid lines. for (int x = 0; x < panelWidth; x += RECT_WIDTH) page.drawLine(x, 0, x, panelHeight); // Draw horizontal grid lines. for (int y = 0; y < panelHeight; y += RECT_HEIGHT) page.drawLine(0, y, panelWidth, y); } // Moves the rectangle. // The rectangle is moved by multiples of its full width or height. public void moveRectangle(int dx, int dy) { theRect.move(dx * RECT_WIDTH, dy * RECT_HEIGHT); } // Draws the RectanglePanel. public void draw() { repaint(); } }