SlideShare a Scribd company logo
1 of 6
Download to read offline
java code please Add event handlers to the buttons in your TicTacToe GUI so that label of the
first button clicked changes to X, the second button clicked changes to O, the third button clicked
changes to X, etc. Clicking a button that already contains an X or O should have no effect. The
Game Status label at the bottom should start out saying "Player 1's turn", and then change to
"Player 2's turn" after the first click, then back to "Player 1's turn" and so on. You do not
need to recognize when the game has ended, but that might be a good challenge to take on if you
have some extra time.
Solution
A)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TicGUI extends JFrame
{
JFrame frame = new JFrame("TicTacToe");
JButton[][] buttons = new JButton[3][3];
JButton start = new JButton("Start");
JButton reset = new JButton("Reset");
JOptionPane turn;
int moveCounter = 9;
boolean gameWon = false;
public TicGUI()
{
super();
frame.setSize(350, 450);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
}
private void checkWin(int row, int col)
{
if(buttons[row][0].getText()==buttons[row][1].getText()&&
buttons[row][1].getText()==buttons[row][2].getText())
{
gameWon = true;
System.out.println(buttons[row][0].getText()+ " wins!!!");
}
else if(buttons[0][col].getText()==buttons[1][col].getText()&&
buttons[1][col].getText()==buttons[2][col].getText())
{
gameWon = true;
System.out.println(buttons[row][0].getText()+ " wins!!!");
}
}
private void compTurn(int count)
{
int randomMove=count;
Random num = new Random();
randomMove = num.nextInt(randomMove)+1;
while(gameWon ==false)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(buttons[i][j].isEnabled()==true)
{
randomMove;
if(randomMove==0 )
{
buttons[i][j].setText("O");
buttons[i][j].setEnabled(false);
moveCounter--;
checkWin(i, j);
}
}
}
}
}
}
private void initialize()
{
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel menu = new JPanel(new BorderLayout());
JPanel game = new JPanel(new GridLayout(3,3));
frame.add(mainPanel);
mainPanel.setPreferredSize(new Dimension(215,315));
menu.setPreferredSize(new Dimension(300,50));
game.setPreferredSize(new Dimension(300,300));
mainPanel.add(menu, BorderLayout.NORTH);
mainPanel.add(game, BorderLayout.SOUTH);
menu.add(start, BorderLayout.WEST);
menu.add(reset, BorderLayout.EAST);
start.addActionListener(new myActionListener());
reset.addActionListener(new myActionListener());
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setText("");
buttons[i][j].setVisible(true);
game.add(buttons[i][j]);
buttons[i][j].addActionListener(new myActionListener());
}
}
}
private class myActionListener implements ActionListener
{ //Implementing action listener for buttons
public void actionPerformed(ActionEvent a)
{
if(a.getSource() == buttons[0][0])
{
buttons[0][0].setText("X");
buttons[0][0].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(0,0);
}
else if(a.getSource() == buttons[0][1])
{
buttons[0][1].setText("X");
buttons[0][1].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(0,1);
}
else if(a.getSource() == buttons[1][0])
{
buttons[1][0].setText("X");
buttons[1][0].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(1,0);
}
else if(a.getSource() == buttons[1][1])
{
buttons[1][1].setText("X");
buttons[1][1].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(1,1);
}
else if(a.getSource() == buttons[1][2])
{
buttons[1][2].setText("X");
buttons[1][2].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(1,2);
}
else if(a.getSource() == buttons[2][2])
{
buttons[2][2].setText("X");
buttons[2][2].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(2,2);
}
else if(a.getSource() == buttons[0][2])
{
buttons[0][2].setText("X");
buttons[0][2].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(0,2);
}
else if(a.getSource() == buttons[2][1])
{
buttons[2][1].setText("X");
buttons[2][1].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(2,1);
}
else if(a.getSource() == buttons[2][0])
{
buttons[2][0].setText("X");
buttons[2][0].setEnabled(false);
moveCounter--;
compTurn(moveCounter);
checkWin(2,0);
}
else if(a.getSource() == start)
{
turn = new JOptionPane("Do you want to go first? ",JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
start.setEnabled(false);
}
else if(a.getSource() == reset)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
buttons[i][j].setText("");
buttons[i][j].setEnabled(true);
gameWon = false;
}
}
}
}
}
public static void main(String[] args)
{
TicGUI game = new TicGUI();
game.initialize();
}
}

More Related Content

Similar to java code please Add event handlers to the buttons in your TicTacToe.pdf

Chapter 03 game input
Chapter 03 game inputChapter 03 game input
Chapter 03 game inputboybuon205
 
import java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfimport java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfannaipowerelectronic
 
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfimport tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfpreetajain
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfFashionColZone
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfasif1401
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfinfo430661
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino Giuseppe Modarelli
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfsales98
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduinomonksoftwareit
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image galleryBoy Jeorge
 
Practice
PracticePractice
PracticeDaman Toor
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityOUM SAOKOSAL
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfarihantsherwani
 
10 awt event model
10 awt event model10 awt event model
10 awt event modelBayarkhuu
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
 
how can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdfhow can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdfmail931892
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
 

Similar to java code please Add event handlers to the buttons in your TicTacToe.pdf (20)

Chapter 03 game input
Chapter 03 game inputChapter 03 game input
Chapter 03 game input
 
import java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdfimport java.util.Scanner; import java.util.Random; public clas.pdf
import java.util.Scanner; import java.util.Random; public clas.pdf
 
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdfimport tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
 
Of class2
Of class2Of class2
Of class2
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdf
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
Html5 game, websocket e arduino
Html5 game, websocket e arduinoHtml5 game, websocket e arduino
Html5 game, websocket e arduino
 
Flash auto play image gallery
Flash auto play image galleryFlash auto play image gallery
Flash auto play image gallery
 
Practice
PracticePractice
Practice
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
Actionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 InteractivityActionscript 3 - Session 6 Interactivity
Actionscript 3 - Session 6 Interactivity
 
The following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdfThe following GUI is displayed once the application startsThe sug.pdf
The following GUI is displayed once the application startsThe sug.pdf
 
10 awt event model
10 awt event model10 awt event model
10 awt event model
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
how can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdfhow can i build this as problem 2 of my code #include iostream.pdf
how can i build this as problem 2 of my code #include iostream.pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 

More from ezzi97

Explain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfExplain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfezzi97
 
executive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfexecutive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfezzi97
 
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfDiscuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfezzi97
 
create a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfcreate a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfezzi97
 
define three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfdefine three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfezzi97
 
Arrange the steps of DNA replication in the order that they occur. D.pdf
Arrange the steps of DNA replication in the order that they occur.  D.pdfArrange the steps of DNA replication in the order that they occur.  D.pdf
Arrange the steps of DNA replication in the order that they occur. D.pdfezzi97
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfezzi97
 
(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdfezzi97
 
1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdfezzi97
 
2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdfezzi97
 
Write one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfWrite one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfezzi97
 
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
Why do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdfWhy do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdf
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdfezzi97
 
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfWrite 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfezzi97
 
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfWhy is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfezzi97
 
Who are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfWho are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfezzi97
 
What was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfWhat was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfezzi97
 
What is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfWhat is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfezzi97
 
What sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfWhat sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfezzi97
 
Link to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfLink to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfezzi97
 
The Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfThe Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfezzi97
 

More from ezzi97 (20)

Explain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdfExplain why multiple processes cannot share data easilySolution.pdf
Explain why multiple processes cannot share data easilySolution.pdf
 
executive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdfexecutive summary for law enforcement using dronesSolutionUse .pdf
executive summary for law enforcement using dronesSolutionUse .pdf
 
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdfDiscuss how your life and experience with social mediaweb 2.0 compa.pdf
Discuss how your life and experience with social mediaweb 2.0 compa.pdf
 
create a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdfcreate a narrative budget blueprint for a local unit of government. .pdf
create a narrative budget blueprint for a local unit of government. .pdf
 
define three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdfdefine three types of kernal-mode to user mode transfersSolution.pdf
define three types of kernal-mode to user mode transfersSolution.pdf
 
Arrange the steps of DNA replication in the order that they occur. D.pdf
Arrange the steps of DNA replication in the order that they occur.  D.pdfArrange the steps of DNA replication in the order that they occur.  D.pdf
Arrange the steps of DNA replication in the order that they occur. D.pdf
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdf
 
(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf(c) After conducting several measurements, the Beijing Municipal Env.pdf
(c) After conducting several measurements, the Beijing Municipal Env.pdf
 
1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf1. Which of the following statements would correctly print out t.pdf
1. Which of the following statements would correctly print out t.pdf
 
2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf2.How important is it to involve physicians in financial improvement.pdf
2.How important is it to involve physicians in financial improvement.pdf
 
Write one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdfWrite one page essay to explain how you relate signals and systems t.pdf
Write one page essay to explain how you relate signals and systems t.pdf
 
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
Why do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdfWhy do IDPs & IDRs lack structure  Lack a ligand or partner  Denatu.pdf
Why do IDPs & IDRs lack structure Lack a ligand or partner Denatu.pdf
 
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdfWrite 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
Write 2 to 3 paragraphs aboutONE DDoS attack that occurred in 2016.pdf
 
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdfWhy is methyl salicylate not appreciably soluble in waterSoluti.pdf
Why is methyl salicylate not appreciably soluble in waterSoluti.pdf
 
Who are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdfWho are stakeholders Define who they are and then please share what.pdf
Who are stakeholders Define who they are and then please share what.pdf
 
What was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdfWhat was the biggest problem with the Articles of Confederation They.pdf
What was the biggest problem with the Articles of Confederation They.pdf
 
What is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdfWhat is UWIN and what does it doSolutionUWin is a software .pdf
What is UWIN and what does it doSolutionUWin is a software .pdf
 
What sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdfWhat sort of archaeological remains have been discovered on the site.pdf
What sort of archaeological remains have been discovered on the site.pdf
 
Link to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdfLink to assignment that I need help with is below httpweb.cse..pdf
Link to assignment that I need help with is below httpweb.cse..pdf
 
The Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdfThe Food Stamp Program is Americas first line of defense against hu.pdf
The Food Stamp Program is Americas first line of defense against hu.pdf
 

Recently uploaded

The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 

Recently uploaded (20)

The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 

java code please Add event handlers to the buttons in your TicTacToe.pdf

  • 1. java code please Add event handlers to the buttons in your TicTacToe GUI so that label of the first button clicked changes to X, the second button clicked changes to O, the third button clicked changes to X, etc. Clicking a button that already contains an X or O should have no effect. The Game Status label at the bottom should start out saying "Player 1's turn", and then change to "Player 2's turn" after the first click, then back to "Player 1's turn" and so on. You do not need to recognize when the game has ended, but that might be a good challenge to take on if you have some extra time. Solution A) import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class TicGUI extends JFrame { JFrame frame = new JFrame("TicTacToe"); JButton[][] buttons = new JButton[3][3]; JButton start = new JButton("Start"); JButton reset = new JButton("Reset"); JOptionPane turn; int moveCounter = 9; boolean gameWon = false; public TicGUI() { super(); frame.setSize(350, 450); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true); frame.setResizable(false); } private void checkWin(int row, int col) { if(buttons[row][0].getText()==buttons[row][1].getText()&&
  • 2. buttons[row][1].getText()==buttons[row][2].getText()) { gameWon = true; System.out.println(buttons[row][0].getText()+ " wins!!!"); } else if(buttons[0][col].getText()==buttons[1][col].getText()&& buttons[1][col].getText()==buttons[2][col].getText()) { gameWon = true; System.out.println(buttons[row][0].getText()+ " wins!!!"); } } private void compTurn(int count) { int randomMove=count; Random num = new Random(); randomMove = num.nextInt(randomMove)+1; while(gameWon ==false) { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(buttons[i][j].isEnabled()==true) { randomMove; if(randomMove==0 ) { buttons[i][j].setText("O"); buttons[i][j].setEnabled(false); moveCounter--; checkWin(i, j); } } } }
  • 3. } } private void initialize() { JPanel mainPanel = new JPanel(new BorderLayout()); JPanel menu = new JPanel(new BorderLayout()); JPanel game = new JPanel(new GridLayout(3,3)); frame.add(mainPanel); mainPanel.setPreferredSize(new Dimension(215,315)); menu.setPreferredSize(new Dimension(300,50)); game.setPreferredSize(new Dimension(300,300)); mainPanel.add(menu, BorderLayout.NORTH); mainPanel.add(game, BorderLayout.SOUTH); menu.add(start, BorderLayout.WEST); menu.add(reset, BorderLayout.EAST); start.addActionListener(new myActionListener()); reset.addActionListener(new myActionListener()); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { buttons[i][j] = new JButton(); buttons[i][j].setText(""); buttons[i][j].setVisible(true); game.add(buttons[i][j]); buttons[i][j].addActionListener(new myActionListener()); } } } private class myActionListener implements ActionListener { //Implementing action listener for buttons public void actionPerformed(ActionEvent a) { if(a.getSource() == buttons[0][0]) { buttons[0][0].setText("X");
  • 4. buttons[0][0].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(0,0); } else if(a.getSource() == buttons[0][1]) { buttons[0][1].setText("X"); buttons[0][1].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(0,1); } else if(a.getSource() == buttons[1][0]) { buttons[1][0].setText("X"); buttons[1][0].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(1,0); } else if(a.getSource() == buttons[1][1]) { buttons[1][1].setText("X"); buttons[1][1].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(1,1); } else if(a.getSource() == buttons[1][2]) { buttons[1][2].setText("X"); buttons[1][2].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(1,2);
  • 5. } else if(a.getSource() == buttons[2][2]) { buttons[2][2].setText("X"); buttons[2][2].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(2,2); } else if(a.getSource() == buttons[0][2]) { buttons[0][2].setText("X"); buttons[0][2].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(0,2); } else if(a.getSource() == buttons[2][1]) { buttons[2][1].setText("X"); buttons[2][1].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(2,1); } else if(a.getSource() == buttons[2][0]) { buttons[2][0].setText("X"); buttons[2][0].setEnabled(false); moveCounter--; compTurn(moveCounter); checkWin(2,0); } else if(a.getSource() == start) { turn = new JOptionPane("Do you want to go first? ",JOptionPane.QUESTION_MESSAGE,
  • 6. JOptionPane.YES_NO_OPTION); start.setEnabled(false); } else if(a.getSource() == reset) { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { buttons[i][j].setText(""); buttons[i][j].setEnabled(true); gameWon = false; } } } } } public static void main(String[] args) { TicGUI game = new TicGUI(); game.initialize(); } }