import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.Vector; class TotalRedraw extends JPanel { final int NUM_ROWS = 500; final int CHECKERBOARD_SIZE = 20; JFrame window = new JFrame(); // list of checkerboard rectangles Vector checkerboardObjs = new Vector(); CheckerboardRect blackRect = new CheckerboardRect(10, 10, 100, 50, Color.black); // variables to handle state information while moving the black rectangle boolean moving = false; // whether or not the rectangle is being moved int leftOffset; // the initial offset of the mouse from the upper int topOffset; // left corner // checkerboard objects will store their color--inefficient storage-wise but // convenient and simplifies the paintComponent code class CheckerboardRect extends Rectangle { Color color; CheckerboardRect(int left, int top, int wd, int ht, Color c) { super(left, top, wd, ht); color = c; } } public TotalRedraw() { int row, col; boolean redFlag; CheckerboardRect r; // create a red and white checkerboard for (row = 0; row < NUM_ROWS; row++) { // start with red on even rows and white on odd rows redFlag = (row % 2 == 0); for (col = 0; col < NUM_ROWS; col++) { r = new CheckerboardRect(col*CHECKERBOARD_SIZE, row*CHECKERBOARD_SIZE, CHECKERBOARD_SIZE, CHECKERBOARD_SIZE, (redFlag ? Color.red : Color.white)); // change the color of the next square redFlag = !redFlag; checkerboardObjs.add(r); } } // code for drawing the black rectangle around the display addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (blackRect.contains(x,y)) { moving = true; leftOffset = x - (int)blackRect.getX(); topOffset = y - (int)blackRect.getY(); } repaint(); } public void mouseReleased(MouseEvent e) { if (moving) { moving = false; blackRect.setLocation(e.getX() - leftOffset, e.getY() - topOffset); } repaint(); } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (moving) { blackRect.setLocation(e.getX() - leftOffset, e.getY() - topOffset); repaint(); } } }); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setContentPane(this); window.pack(); window.setVisible(true); } public Dimension getPreferredSize() { return new Dimension(400, 400); } public Dimension getMinimumSize() { return new Dimension(400, 400); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; Color saveColor = g.getColor(); // make the background white g2.setColor(Color.white); g2.clearRect(0, 0, getWidth(), getHeight()); // draw the checkerboard int i = 0; for (CheckerboardRect r : checkerboardObjs) { i++; g2.setColor(r.color); g2.fill(r); } // draw the black rectangle g2.setColor(blackRect.color); g2.fill(blackRect); g2.setColor(saveColor); } public static void main(String args[]) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new TotalRedraw(); } }); } }