Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 7 ■ WRITING A USER INTERFACE


@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
}

@Override
public void mouseReleased(MouseEvent e) {
JButton clickedButton = (JButton) e.getSource();
for (int i = 0; i < mineSweeper.rows; i++) {
for (int j = 0; j < mineSweeper.columns; j++) {
if (clickedButton == mineSweeper.mineButtons[i][j]) {
MineField.gameState state;
if (e.getButton() == MouseEvent.BUTTON1) {
state = mineSweeper.mineField.resolveClick(i,j, true);
if (state == MineField.gameState.CONTINUE) {
if (mineSweeper.mineField.getMineFlag(i, j) == Mine.flagState.UNKNOWN) {
clickedButton.removeMouseListener(this);
}
}
} else {
state = mineSweeper.mineField.resolveClick(i,j, false);
}
if (state == MineField.gameState.WIN) {
mineSweeperHelper.endGame(true);
} else if (state == MineField.gameState.LOSE){
mineSweeperHelper.endGame(false);
} else {
mineSweeperHelper.updateButtons();
}
}
}
}
mineSweeperHelper.updateLabels();
}
}

As we saw in the MineSweeperHelper class, the MineSweeperMouseListener class has a constructor that
it uses to get an instance of the MineSweeper class. It also gets an instance of the MineSweeperHelper class.
Both of those classes need to listen for mouse clicks, so the MineSweeperMouseListener class has to have
instances of both classes. The only other method that does anything is the mouseReleased method. As we
learn earlier, using the mouseReleased method is more reliable than using the mouseClicked method,
thanks to the problem of mouse motion wiping out the click event.
The mouseClicked method runs through all the buttons until it finds the button on which the player
clicked. If the player clicked the left mouse button, the method calls the resolveClick method in the
MineField class to see whether the player hit a mine. If not, the resolveClick method figures out whether
Free download pdf