I'm working on a simple GUI project to get the foundations of Java Swing. I created a Rock Paper Scissors game which you play against the computer which i implemented a GUI for
My text based GUI Form for Rock, Paper,Scissors
My problem is that once either my score or the computers score reach a value of 3, i want the text on the frame to change. I've tried to implement the code to check each time the variable increases in the button function but it still does not works, neither does implementing the function in the main, the game doesn't change any text or stop once the scores reach 3.
chooseRock.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cc = getCompChoice();
if (cc.equalsIgnoreCase("Paper")) {
compcount++;
if(compcount == 3){
winner.setText("Computer Wins");
}
compChoice.setText("Computers Choice: " + cc);
This code shows the GUI object and the listener for selecting "Rock", the code is the same for both paper and Scissors. Both compchoice and playchoice are declared with the other attributes at the top.
gameScreen(String title){
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(gameBoard);
this.pack();
chooseRock.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cc = getCompChoice();
if (cc.equalsIgnoreCase("Paper")) {
compcount++;
compChoice.setText("Computers Choice: " + cc);
compScore.setText("Computer Score: " + compcount);
} else if (cc.equalsIgnoreCase("Scissors")) {
playcount++;
compChoice.setText("Computers Choice: " + cc);
playerScore.setText("Your Score: " + playcount);
} else {
compChoice.setText("Computers Choice: " + cc + " Its a DRAW!");
}
}
});
This is a function I've written to check the scores and display the winner, the 'winner' text is displayed at the top of the panel and has a placeholder.
public void checkScore(){
if(playcount == 3 ){
winner.setText("GAME OVER - PLAYER WINS");
chooseRock.setEnabled(false);
chooseScissors.setEnabled(false);
choosePaper.setEnabled(false);
}else if(compcount == 3 ){
winner.setText("GAME OVER - COMPUTER WINS! BETTER LUCK NEXT TIME");
chooseRock.setEnabled(false);
chooseScissors.setEnabled(false);
choosePaper.setEnabled(false);
}
}
Is there any way to take the variable written inside the listener and use it to change the text field or is there some way conditions like this should be implemented?