This tictactoe program is a 2player game. The GUI i made are frame and buttons after that i started coding. Actually my program is working in this kind of coding.
private String letter= " ";
private int count= 0;
private void btn7ActionPerformed(java.awt.event.ActionEvent evt) {
count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
letter = "X";
} else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
letter = "O";
}
if(evt.getSource() == btn1){
btn1.setText(letter);
} else if(evt.getSource() == btn2){
btn2.setText(letter);
} else if(evt.getSource() == btn3){
btn3.setText(letter);
} else if(evt.getSource() == btn4){
btn4.setText(letter);
} else if(evt.getSource() == btn5){
btn5.setText(letter);
} else if(evt.getSource() == btn6){
btn6.setText(letter);
} else if(evt.getSource() == btn7){
btn7.setText(letter);
} else if(evt.getSource() == btn8){
btn8.setText(letter);
} else if(evt.getSource() == btn9){
btn9.setText(letter);
}
}
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
count++;
if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
letter = "X";
} else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10){
letter = "O";
}
if(evt.getSource() == btn1){
btn1.setText(letter);
} else if(evt.getSource() == btn2){
btn2.setText(letter);
} else if(evt.getSource() == btn3){
btn3.setText(letter);
} else if(evt.getSource() == btn4){
btn4.setText(letter);
} else if(evt.getSource() == btn5){
btn5.setText(letter);
} else if(evt.getSource() == btn6){
btn6.setText(letter);
} else if(evt.getSource() == btn7){
btn7.setText(letter);
} else if(evt.getSource() == btn8){
btn8.setText(letter);
} else if(evt.getSource() == btn9){
btn9.setText(letter);
Yeah, it is actually working but my problem with this codes is I need to put the codes in every button e.g. button7, button1 (these just the example of my buttons) which is the codes are the action performed of the button.
I want only a single command that each button perform and I dont want to copy paste in every buttons because they are identical codes. I think there is a code to do that, what do you think? Please help!
So basically, you want to collapse you logic into a single handler. This handler needs a single reference to the button that it is acting on…
Something like…
Now you setup code may be different then this, this is just an example…
The basic idea is that as you create a new button, you assign it’s own
ActionHandlerpassing it a reference of the button. This allows the action handler to control the button based on the state of the game.