// Write an applet that displays 8 by 8 grid. When clicking on an empty // square, a filled rectangle is displayed. When clicking on the filled // square, the filled rectangle there disappears. Illustrates MouseListener // and adapter classes. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class QueensApplet extends JApplet { private boolean [][] board = new boolean [8][8]; private Container contentPane; public void init () { contentPane = getContentPane(); contentPane.setBackground(Color.white); // initialize the board array for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) board[i][j] = false; addMouseListener (new BoardMouseListener ()); } public void paint (Graphics g) { super.paint(g); // draw the board's vertical lines g.drawLine (0, 0, 0, 400); g.drawLine (50, 0, 50, 400); g.drawLine (100, 0, 100, 400); g.drawLine (150, 0, 150, 400); g.drawLine (200, 0, 200, 400); g.drawLine (250, 0, 250, 400); g.drawLine (300, 0, 300, 400); g.drawLine (350, 0, 350, 400); g.drawLine (400, 0, 400, 400); // draw the board's horizontal lines g.drawLine (0, 0, 400, 0); g.drawLine (0, 50, 400, 50); g.drawLine (0, 100, 400, 100); g.drawLine (0, 150, 400, 150); g.drawLine (0, 200, 400, 200); g.drawLine (0, 250, 400, 250); g.drawLine (0, 300, 400, 300); g.drawLine (0, 350, 400, 350); g.drawLine (0, 400, 400, 400); for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (board[i][j]) g.fillRect(50*i, 50*j, 50, 50); } private class BoardMouseListener extends MouseAdapter { public void mouseClicked (MouseEvent e) { // get coordinates of the mouse click int x_coord = e.getX (); int y_coord = e.getY (); // convert x_coord and y_coord into board's row and column #'s int row = x_coord/50; int column = y_coord/50; board[row][column] = !board[row][column]; repaint(); } } }