Page 744 - Introduction to Programming with Java: A Problem Solving Approach
P. 744

                710 Chapter 17 GUI Programming—Component Layout, Additional GUI Components
 }
// end class TicTaAcTpoeago PDF Enhancer
//***********************************************************
// If user clicks a button, change its label to "X" or "O".
private class Listener implements ActionListener
{
{
}
public void actionPerformed(ActionEvent e)
{
}
JButton btn = (JButton) e.getSource();
if (btn.getText().isEmpty())
{
}
btn.setText(xTurn ? "X" : "O");
xTurn = !xTurn;
// end actionPerformed
} // end class Listener
//***********************************************************
public static void main(String[] args)
new TicTacToe();
Figure 17.7b TicTacToe program—part B
specifically, if xTurn is false, we assign true into xTurn. And if xTurn is true, we assign false
into xTurn.
17.7 Problem Solving: Winning at Tic-Tac-Toe (Optional)
As you might have noticed, the previous section’s TicTacToe program doesn’t check for a winning move. As a problem-solving exercise, let’s now discuss how to add that functionality. Rather than provide you with a Java solution, we’ll provide you with the thought process for coming up with a solution. We’ll codify the thought process using pseudocode. One of chapter’s projects asks you to finish the
job by implementing a complete Java program solution.
To check for a win (i.e., to check for three in a row, three in a column, or three in a diagonal), the
listener needs to access multiple buttons. As it stands now, the TicTacToe listener can access only one button—the button that was clicked. It gets that button by calling getSource. So how should you change the program so the listener can access multiple buttons?
To access multiple buttons, you need to declare multiple buttons. You could declare nine separate but- tons, but the more elegant solution is to declare a three-row, three-column, two-dimensional array of but- tons. The next question is, where should you declare the array? Do you declare it as a local variable inside the listener or as an instance variable at the top of the program? In general, local variables are preferred, but in this case, a local variable won’t work. Local variables don’t persist. You need to be able to update a button
   Iterate to enhance.
 

































































   742   743   744   745   746