/** * Minesweeper.java * */ import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class Minesweeper extends Frame implements MouseListener, WindowListener { private Rectangle [][] theGrid; private int rowClicked; private int colClicked; private final int SIZE = 3; private final int WIDTH = 500; private final int HEIGHT = 500; private final int CELL_WIDTH = WIDTH/SIZE; private final int CELL_HEIGHT = HEIGHT/SIZE; public Minesweeper() { Dimension rectDim = new Dimension(CELL_WIDTH, CELL_HEIGHT); theGrid = new Rectangle [SIZE][SIZE]; for(int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { Point upperLeft = new Point(150 + CELL_WIDTH*col, 50 + CELL_HEIGHT * row); theGrid[row][col] = new Rectangle(upperLeft, rectDim); } } setBackground(Color.white); rowClicked = -1; colClicked = -1; this.addMouseListener(this); this.addWindowListener(this); } // The following methods are required to implement a MouseListener public void mouseClicked(MouseEvent evt) { Point pointClicked = evt.getPoint(); for(int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { if(theGrid[row][col].contains(pointClicked)) { rowClicked = row; colClicked = col; } } } repaint(); } public void mouseEntered(MouseEvent evt) { /* no action */ } public void mouseExited(MouseEvent evt) { /* no action */ } public void mousePressed(MouseEvent evt) { /* no action */ } public void mouseReleased(MouseEvent evt) { /* no action */ } public void paint(Graphics g) { g.setColor(Color.blue); if(rowClicked != -1 && colClicked != -1) { g.fillRect(theGrid[rowClicked][colClicked].x, theGrid[rowClicked][colClicked].y, theGrid[rowClicked][colClicked].width, theGrid[rowClicked][colClicked].height); } g.setColor(Color.black); for(int row = 0; row < SIZE; row++) { for (int col = 0; col < SIZE; col++) { g.drawRect(theGrid[row][col].x, theGrid[row][col].y, theGrid[row][col].width, theGrid[row][col].height); } } } public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } }