Tic-Tac-Toe is a very common game that is fairly easy to play. The rules of the game are simple and well-known. Because of these things, Tic-Tac-Toe is fairly easy to code up. In this tutorial, we will be looking at how to code a working game of Tic-Tac-Toe in Java. This tutorial assumes that you. Author: Graham Mitchell; Filename: TicTacToe.java; Tic-Tac-Toe. Code an interactive, two-player game of Tic-Tac-Toe. You'll use a two-dimensional array of chars. Starter Code. We cover a simple Java class that you can use in your Java programs to implement a game of Tic-Tac-Toe. Code Library. C and C++; Java Programming.
I am trying to make a Tic Tac Toe program with java swing, and I have the frame made. How can I go about making the buttons in the JButton array activate the int array? I want the int array to hold the values for the spots in the Tic Tac Toe grid, so when a button is pressed, the corresponding spot in the int array will be a 0 or a 1, and the text of the button will change to an X or an O.
3 Answers
You could create your own JButton
implementation and supply an index value to. That we you could extract it from the ActionListener
Java Tic Tac Toe Program
Then when you set it up, you could:
This would also allow you to store the state of the button internally...
You might also like to look at JToggleButton
MadProgrammerMadProgrammerassuming the JButton indexes mirror the int array, you could search for the JButton being pressed (e.getSource()
in actionPerformed
) in the button array, but you have to put button array as instance variable of the class so you can use it from other methods, esp. the actionPerformed()
. Once you find the indexes, simply update it's corresponding value in the int array.
Use JButton's setActionCommand method to set the action command in button[0][0] to '00' and the command from button[2][1] to '21'. this ill let you get the position easily right from actionPerformed. Also, you need three states, not just 2. If you're not sure what I'm talking about, play a game of tic-tac-toe and write down the array about halfway through.
Jakob WeisblatJakob Weisblat