import java.applet.Applet; import java.awt.Rectangle; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; /** This program will show many squares in an applet. Each time you click on * one, it will turn blue (until you click on a different square). */ public class MouseApplet3 extends Applet { private Rectangle [][] box; private int row; private int col; public void init() { // When drawing the boundaries of the squares, j refers to the inner // loop which is the column number, which corresponds to x. And so // i corresponds to y. (At first this may seem backwards!) box = new Rectangle[8][8]; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) box[i][j] = new Rectangle(35*j,35*i,35,35); DetectInput listener = new DetectInput(); addMouseListener(listener); } class DetectInput implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); // set row and col based on x and y row = y / 35; col = x / 35; repaint(); } public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.blue); g2.fill(box[row][col]); for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) g2.draw(box[i][j]); } }