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

                17.6 Tic-Tac-Toe Example 707
 Now for a couple of things to watch out for. As you know, there’s special significance when you call the GridLayout constructor with rows = 0 or columns = 0. It puts the GridLayout manager in charge of choosing the number of rows or the number of columns. But it only works if you have one 0-value argument, not two. If you call the GridLayout constructor with two 0-value arguments, you’ll get a compile-time error.
What about the opposite case—when you call the GridLayout constructor with two non-0 values for the rows and columns arguments. That’s fine as long as your table is completely filled. If it’s not completely filled, you might get unexpected results. For example, the above four-column window is not completely filled. Suppose you accidentally specify a value for the rows argument:
setLayout(new GridLayout(2, 4));
Here’s what the program displays:
          Apago PDF Enhancer
Now that’s strange! There are three columns even though we specified four. Moral of the story: Call the
2
In this section, we present a simple tic-tac-toe program. We’ve chosen tic-tac-toe because we wanted to illustrate GridLayout details. And tic-tac-toe, with its three-row by three-column board, provides the perfect opportunity for that.
User Interface
The program initially displays a three-row, three-column grid of blank buttons. Two users, player X and player O, take turns clicking blank buttons. Player X goes first. When player X clicks a button, the button’s label changes from blank to X. When player O clicks a button, the button’s label changes from blank to O.
2 Here’s the inside skinny. If you call the GridLayout constructor with two non-0 values for the rows and columns arguments, the columns argument is ignored and the GridLayout manager determines the number of columns on its own. For the case where you have two non-0 values and the table is completely filled, the GridLayout manager still determines the number of columns on its own. But the determined number of columns works out perfectly (that is, the determined number of columns matches the specified number of columns).
 GridLayout constructor with two non-0 values only if your table is completely filled. 17.6 Tic-Tac-Toe Example
  





















































































   739   740   741   742   743