package week1; /* This applet draws a red-and-black checkerboard. It is assumed that the size of the applet is 160 by 160 pixels. When the user clicks a square, that square is selected, unless it is already selected. When the user clicks the selected square, it is unselected. If there is a selected square, it is hilited with a cyan border. */ import java.awt.*; import java.awt.event.*; import java.applet.*; public class ClickableCheckerboard extends Applet implements MouseListener{ int selectedRow; // Row and column of selected square. If no int selectedCol; // square is selected, selectedRow is -1. public void init() { // Initialize the applet. Set selectedRow to -1 to indicate // that no square is selected. And listen for mouse events. selectedRow = -1; selectedCol = -1; addMouseListener(this); } public void update(Graphics g) { // Since the paint method paints the whole applet, there is // no need to fill it with the background color first. To // avoid flickering, redefine update so it just calls paint. paint(g); } public void paint(Graphics g) { // Draw the checkerboard and hilite the selected square, if any. int row; // Row number, from 0 to 7 int col; // Column number, from 0 to 7 int x,y; // Top-left corner of square for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++) { x = col * 20; y = row * 20; if ( (row % 2) == (col % 2) ) g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(x, y, 20, 20); } } // end for row if (selectedRow <= 8) { // Since there is a selected square, draw a cyan // border around it. g.setColor(Color.cyan); y = selectedRow * 20; x = selectedCol * 20; g.drawRect(x, y, 19, 19); g.drawRect(x+1, y+1, 17, 17); } if (selectedCol <= 8) { // Since there is a selected square, draw a cyan // border around it. g.setColor(Color.cyan); y = selectedRow * 20; x = selectedCol * 20; g.drawRect(x, y, 19, 19); g.drawRect(x+1, y+1, 17, 17); } } // end paint() public void mousePressed(MouseEvent evt) { // When the user clicks on the applet, figure out which // row and column the click was in and change the // selected square accordingly. int col = evt.getX() / 20; // Column where user clicked. int row = evt.getY() / 20; // Row where user clicked. if (selectedRow == row && selectedCol == col) { // User clicked on the currently selected square. // Turn off the selection by setting selectedRow to -1. selectedRow = -1; } else { // Change the selection to the square the user clicked on. selectedRow = row; selectedCol = col; } repaint(); } // end mouseDown() public void mouseReleased(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } } // end class