// March 5, 2004 (Previously Feb 27) - 6_David_Sharp_Chris import javax.swing.*; import java.awt.*; import java.awt.geom.*; // The class draws the rectangles, the border if required, and // fills in the rectangles with the specified colors. public class RectanglesPanel extends JPanel { private int myRows,myCols,myOldRows,myOldCols,myMouseX,myMouseY; private Color myColor; private Color [][] myColors; private boolean myGrid; private boolean myMouseValid = false; // Initialize with mouse invalid and not clicked. public RectanglesPanel(int rows, int cols) { myColors = new Color[rows][cols]; for (int i=0; i 0) // Draw left and right borders. { if (i%2 == 0) // Even pixels. { leftBorder = i/2 - 1; rightBorder = width - i/2; } else // Odd pixels. { leftBorder = (i+1)/2 - 1; rightBorder = width - (i-1)/2; } } else // Set borders off screen, i.e. none. { leftBorder = -1.0; rightBorder = width + 1; } i = height%myRows; if (i > 0) // Draw top and bottom borders. { if (i%2 == 0) // Even pixels. { topBorder = i/2 - 1; bottomBorder = height - i/2; } else // Odd pixels. { topBorder = (i+1)/2 - 1; bottomBorder = height - (i-1)/2; } } else // Set borders off screen, i.e. none. { topBorder = -1; bottomBorder = height + 1; } g2.setPaint(Color.BLACK); // Draw borders if required. Line2D.Double line = new Line2D.Double(); if (leftBorder >= 0) { for (i=0; i<=leftBorder; i++) { line.setLine(i, 0, i, height); g2.draw(line); } } if (rightBorder < width) { for (i=(int)rightBorder; i= 0) { for (i=0; i<=topBorder; i++) { line.setLine(0, i, width,i); g2.draw(line); } } if (bottomBorder < height) { for (i=(int)bottomBorder; i leftBorder && myMouseX < rightBorder && myMouseY > topBorder && myMouseY < bottomBorder) myMouseValid = true; // Draw colred rectangles, updated with last mouse click if valid. Rectangle2D.Double box = new Rectangle2D.Double(); for (i=0; i= myMouseX && top + colPixels - 1 >= myMouseY) { // Trap invalid mouse click on grid. if (myGrid && (left + rowPixels - 1 == myMouseX || top + colPixels - 1 == myMouseY)) myMouseValid = false; myMouseX = -1; myMouseY = -1; // Fill in rectangle with selected color, then set // mouse to invalid. if (myMouseValid) { myColors[i][j] = myColor; g2.setPaint(myColor); g2.fill(box); myMouseValid = false; } } } } // Draw grid lines if selected. if (myGrid) { g2.setPaint(Color.BLACK); double coord; for (i = 0; i