Reputation: 133
Working on a simple tic-tac-toe game in Java.
I have a class named GameHelpers
. This class should contain useful methods for the game. The game happenes in another class.
A method in GameHelpers
is ResetGame()
. This method is supposed to set the text on all the 9 buttons (the tic-tac-toe board) to blank, set them enabled again, and set a variable to 1.
This is it's code:
public class GameHelpers {
public void resetGame(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
buttons[i][j].setEnabled(true);
buttons[i][j].setText("");
count = 1;
}
}
}
}
buttons[]
is an array of JButtons inside the main class of the game, TicTacToe
.
This method was previously inside the main class of the game, TicTacToe
. But now that it's in a different class, it can't reach the buttons in the TicTacToe
class and manipulate them.
I created get and set methods in TicTacToe
, but how do I activate them from GameHelpers
?
How can I make the method in GameHelpers
work?
Upvotes: 2
Views: 197
Reputation: 285405
You can get the source button that was pushed via the ActionEvent's getSource()
method.
so for example:
public void actionPerformed(ActionEvenet e){
JButton sourceBtn = (JButton) e.getSource();
String text = sourceBtn.getText().trim();
if (text.isEmpty()) { // see if x/o assigned yet
sourceBtn.setText(....); / "X" or "O" depending on logic
}
}
This way, all 9 buttons can share the exact same ActionListener, and the program will still work.
Edit
You state in comment:
Why the trim() thing?
I figure that you've got a tic-tac-toe game going on here, and if so, that you don't want to add an "X" to a JButton that already displays either X or O text. If perchance you've given the JButton a space " "
for text, the trim()
will get rid of any leading or trailing whitespace and will change the text to ""
, and you'll know that it can accept new text, either an "X" or an "O". If you don't need it, then don't use it.
Upvotes: 4