Mathew had some great responses, but I'd like to explain a little more about using for loops. If you take a look at your Board()
code right now, you might notice how a lot of the code is the same - when you make the JButton
s, for example, you call new JButton("")
nine times in a row. In general, having a lot of code that all looks the same or is copy-pasted is a bad idea. You can use a for loop with an array to clean this up a lot. Here's how Board()
would look after using an array.
Board() { // creates the panel setLayout(new GridLayout(3, 3)); buttons = new JButton[9]; for (int i=0; i < buttons.length; i++) { buttons[i] = new JButton(""); } SetGame(); for (int i=0; i < buttons.length; i++) { add(buttons[i]); buttons[i].addActionListener(this); } }
See how much shorter and less repetitive that is?
As a side note, by not specifying 'public' or 'private', you implicitly made your constructors package-private, which is rarely the right solution. I recommend specifying everything as either public or private, until you get to the point of distributing your code or compiled programs, in which case package-private might occasionally make sense.