19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

690 Chapter 18 Applets and Multimedia<br />

register listener<br />

paint cell<br />

listener class<br />

main method omitted<br />

79 public Cell() {<br />

80 setBorder(new LineBorder(Color.black, 1)); // Set cell's border<br />

81 addMouseListener(new MyMouseListener()); // Register listener<br />

82 }<br />

83<br />

84 /** Return <strong>to</strong>ken */<br />

85 public char getToken() {<br />

86 return <strong>to</strong>ken;<br />

87 }<br />

88<br />

89 /** Set a new <strong>to</strong>ken */<br />

90 public void setToken(char c) {<br />

91 <strong>to</strong>ken = c;<br />

92 repaint();<br />

93 }<br />

94<br />

95 @Override /** Paint the cell */<br />

96 protected void paintComponent(Graphics g) {<br />

97 super.paintComponent(g);<br />

98<br />

99 if (<strong>to</strong>ken == 'X') {<br />

100 g.drawLine(10, 10, getWidth() - 10, getHeight() - 10);<br />

101 g.drawLine(getWidth() - 10, 10, 10, getHeight() - 10);<br />

102 }<br />

103 else if (<strong>to</strong>ken == 'O') {<br />

104 g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);<br />

105 }<br />

106 }<br />

107<br />

108<br />

109<br />

private class MyMouseListener extends MouseAdapter {<br />

@Override /** Handle mouse click on a cell */<br />

110 public void mouseClicked(MouseEvent e) {<br />

111 // If cell is empty and game is not over<br />

112 if (<strong>to</strong>ken == ' ' && whoseTurn != ' ') {<br />

113 setToken(whoseTurn); // Set <strong>to</strong>ken in the cell<br />

114<br />

115 // Check game status<br />

116 if (isWon(whoseTurn)) {<br />

117 jlblStatus.setText(whoseTurn + " won! The game is over");<br />

118 whoseTurn = ' '; // Game is over<br />

119 }<br />

120 else if (isFull()) {<br />

121 jlblStatus.setText("Draw! The game is over");<br />

122 whoseTurn = ' '; // Game is over<br />

123 }<br />

124 else {<br />

125 // Change the turn<br />

126 whoseTurn = (whoseTurn == 'X') ? 'O' : 'X';<br />

127 // Display whose turn<br />

128 jlblStatus.setText(whoseTurn + "'s turn");<br />

129 }<br />

130 }<br />

131 }<br />

132 }<br />

133 }<br />

134 }<br />

The TicTacToe class initializes the user interface with nine cells placed in a panel of<br />

GridLayout (lines 19–22). A label named jlblStatus is used <strong>to</strong> show the status of the<br />

game (line 14). The variable whoseTurn (line 8) is used <strong>to</strong> track the next type of <strong>to</strong>ken <strong>to</strong> be

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!