Java Reference
In-Depth Information
79 public Cell() {
80 setBorder( new LineBorder(Color.black, 1 )); // Set cell's border
81
addMouseListener( new MyMouseListener());
// Register listener
register listener
82 }
83
84
/** Return token */
85
public char getToken() {
86
return token;
87 }
88
89 /** Set a new token */
90 public void setToken( char c) {
91 token = c;
92 repaint();
93 }
94
95 @Override /** Paint the cell */
96
protected void paintComponent(Graphics g)
{
paint cell
97
super .paintComponent(g);
98
99 if (token == 'X' ) {
100 g.drawLine( 10 , 10 , getWidth() - 10 , getHeight() - 10 );
101 g.drawLine(getWidth() - 10 , 10 , 10 , getHeight() - 10 );
102 }
103 else if (token == 'O' ) {
104 g.drawOval( 10 , 10 , getWidth() - 20 , getHeight() - 20 );
105 }
106 }
107
108
109 @Override /** Handle mouse click on a cell */
110 {
111 // If cell is empty and game is not over
112 if (token == ' ' && whoseTurn != ' ' ) {
113 setToken(whoseTurn); // Set token in the cell
114
115 // Check game status
116 if (isWon(whoseTurn)) {
117 jlblStatus.setText(whoseTurn + " won! The game is over" );
118 whoseTurn = ' ' ; // Game is over
119 }
120 else if (isFull()) {
121 jlblStatus.setText( "Draw! The game is over" );
122 whoseTurn = ' ' ; // Game is over
123 }
124 else {
125 // Change the turn
126 whoseTurn = (whoseTurn == 'X' ) ? 'O' : 'X' ;
127 // Display whose turn
128 jlblStatus.setText(whoseTurn + "'s turn" );
129 }
130 }
131 }
132 }
133 }
134 }
private class MyMouseListener extends MouseAdapter {
listener class
public void mouseClicked(MouseEvent e)
main method omitted
The TicTacToe class initializes the user interface with nine cells placed in a panel of
GridLayout (lines 19-22). A label named jlblStatus is used to show the status of the
game (line 14). The variable whoseTurn (line 8) is used to track the next type of token to be
 
Search WWH ::




Custom Search