I am completing a past paper exam question and it asks to create an applet that displays a green square in the center, with three buttons + , - and reset, however, I am trying to make it that when any button is clicked the program should essentially figure out which button was pressed. I know you would use e.getSource() but I am not sure how to go about this.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Square extends JApplet {
int size = 100;
public void init() {
JButton increase = new JButton("+");
JButton reduce = new JButton("-");
JButton reset = new JButton("reset");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(increase);
butPanel.add(reduce);
butPanel.add(reset);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
ButtonHandler bh1 = new ButtonHandler(this, 0);
ButtonHandler bh2 = new ButtonHandler(this, 1);
ButtonHandler bh3 = new ButtonHandler(this, 2);
increase.addActionListener(bh1);
reduce.addActionListener(bh2);
reset.addActionListener(bh3);
}
}
class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(10, 10, theApplet.size, theApplet.size);
}
}
class ButtonHandler implements ActionListener {
Square theApplet;
int number;
ButtonHandler(Square app, int num) {
theApplet = app;
number = num;
}
public void actionPerformed(ActionEvent e) {
switch (number) {
case 0:
theApplet.size = theApplet.size + 10;
theApplet.repaint();
break;
case 1:
if (theApplet.size > 10) {
theApplet.size = theApplet.size - 10;
theApplet.repaint();
}
break;
case 2:
theApplet.size = 100;
theApplet.repaint();
break;
}
}
Not the best way to do it, but based on your current code, you could simply compare the object references. You'd need to pass in references to the buttons or access them some other way. e.g.
if(e.getSource() == increase) { \\do something on increase}
Another alternative would be to check the string of the button, e.g.
if(((JButton)e.getSource()).getText().equals("+")){ \\do something on increase}
You can use strings in a switch statement in Java 8, but if you're using Java 7 or lower, it has to be an if statement.
You can use if then else statement as in the sample below
if(e.getSource()==bh1){
//your codes for what should happen
}else if(e.getSource()==bh2){
}else if(e.getSource()==bh3){
}else if(e.getSource()==bh4){
}
OR even in a switch case statement
Related
import javax.swing.JFrame;
public class ClickingGame extends javax.swing.JFrame {
int difficulty;
public int diffRec(int diff) {
diff = difficulty;
return (difficulty);
}
public ClickingGame() {
initComponents();
}
private void comboDifficultyActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ClickingGamePanel panel = new ClickingGamePanel();
JFrame frame = new JFrame("Clicker Precison");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
switch (comboDifficulty.getSelectedIndex()) {
case 0:
difficulty = 1;
break;
case 1:
difficulty = 2;
break;
case 2:
difficulty = 3;
break;
default:
break;
}
then i try calling the method diffRec in another class but it will error
public ClickingGamePanel() {
ClickingListener mouse = new ClickingListener();
addMouseMotionListener(mouse);
addMouseListener(mouse);
Circle = new Circle();
ClickingGame = new ClickingGame();
ClickingGame. ???
when i try call diffRec into the panel it won't show DiffRec as an option. Any help for a noob like me? sorry for bad formatting, it is my first time posting
When you create objects remember to give them a name. They need a way to be referenced. Otherwise, if there were multiple ClickingGame objects the program wouldn't know which one you were referring to.
Circle c = new Circle();
ClickingGame cg = new ClickingGame();
cg.diffRec(value);
This should give you access to the method.
I'm wondering why my applet isn't running. I'm using netbeans, and the program works fine with no errors, but I can't seem to get the applet screen to appear to test all the functions of my program.I was wondering if someone can point out what I am doing wrong in starting my applet up. I haven't done to many things with applets, so I'm quite curious why it isn't upping and running for me. I really didn't want to post the full code of my program, but I've no idea if there's an error in my code, or I'm just not doing the right thing to actually start the applet or something.
I do not get any errors while running my program, that applet simply does not appear and run in itself. Otherwise I get no errors from neatbeans while running my program.
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.FlowLayout;
public class Program7 extends JApplet implements ActionListener, ItemListener
{
//static varaibles
private static int GuiHeight = 90;
private static int Square = 50;
//gui varaibles
private JRadioButton drawSquare;
private JRadioButton mess;
private JTextField messageFeild;
private JCheckBox color;
private JButton button;
private JComboBox location;
//modable global varaibles
private int width, height, drawX, drawY;
private Color drawColor;
private String draw;
#Override
public void init()
{
//creating the panels
JPanel drawChoice;
JPanel drawSet;
//setting group onject to link certain buttons together
ButtonGroup ObjGroup;
//setting layout to make things look nice
setLayout(new FlowLayout());
//ibtializing other varaibles
width = 0;
height = 0;
drawX = 0;
drawY= 0;
drawColor = Color.BLACK;
draw = "";
//intialzing the gui interface
drawSquare = new JRadioButton("Draw a Square!");
mess = new JRadioButton("Write a Message!");
location = new JComboBox(new String[]{"", "Random Pick", "Top Left"});
color = new JCheckBox("Draw in Color!");
button = new JButton("Draw it!");
//linking the buttons together
ObjGroup = new ButtonGroup();
ObjGroup.add(drawSquare);
ObjGroup.add(mess);
//adding event handlers to the buttons
location.addItem(this);
button.addActionListener(this);
color.addItemListener(this);
drawSquare.addActionListener(this);
mess.addActionListener(this);
messageFeild = new JTextField(20);
//adding to the first paels
drawChoice = new JPanel();
drawChoice.add(drawSquare);
drawChoice.add(mess);
drawChoice.add(messageFeild);
//adding to the applet
add(drawChoice);
//adding to the second panel
drawSet = new JPanel();
drawSet.add(new JLabel("Select where to draw!"));
drawSet.add(location);
drawSet.add(color);
drawSet.add(button);
//adding to the applet
add(drawSet);
}
#Override
public void paint(Graphics g)
{
//calling super constructor
super.paint(g);
//getting width
width = getWidth();
height = getHeight();
//setting graphics color
g.setColor(drawColor);
if (location.getSelectedItem() != "")
{
//ifstatement checking for inputs
if(draw == "Square"||draw == "square"||draw == "SQUARE")
{
//creating rectange
g.fillRect(drawX, drawY, width, height);
}
if(draw == "Message"|| draw == "MESSAGE"||draw == "message")
{
//writing message
g.drawString(messageFeild.getText(), drawX, drawY);
}
}
}
#Override
public void actionPerformed(ActionEvent e)
{
//repainting
repaint();
}
#Override
public void itemStateChanged(ItemEvent e)
{
//if statement checking for the various changes being made by the user in the pograms interface
//if statement check checking to see if there's a square or to write a message
if (e.getSource() == drawSquare && e.getStateChange() == ItemEvent.SELECTED)
{
draw = "Square";
messageFeild.setEnabled(false);
}
if (e.getSource() == mess && e.getStateChange() == ItemEvent.SELECTED)
{
draw = "Message";
messageFeild.setEnabled(true);
}
//if statement set checking for locational input
if (e.getSource() == location)
{
if(location.getSelectedItem() == "Random Pick")
{
drawX=(int)(Math.random()*(width+1));
drawY=(int)(GuiHeight+ Math.random()*(height-GuiHeight+1));
}
if(location.getSelectedItem() == "Top Left")
{
drawX=0;
drawY=GuiHeight;
}
}
//if statement to check for color change
if(e.getSource()==color && e.getStateChange()==ItemEvent.SELECTED)
{
drawColor = Color.GREEN;
}
if(e.getSource()==color && e.getStateChange()==ItemEvent.DESELECTED)
{
drawColor = Color.BLACK;
}
}
public static void main(String[] args) {
}
}
I cannot enter two digit number to be calculator. I also cannot get the clear C operator working as well. My dot sign seems to be not working as well. The code below creates a calculator using java swing and does addition, multiplication,subtraction and divisiion of a single digit number.
//First the necessary packages are imported
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**#return a BODMAS calculator using Javax Swing and awt
* *#author Cihan Altunok
*#version 1
*/
//implementing ActionListener to listen to events. JFrame is also extended to add support to Swing components
public class Calculator extends JFrame implements ActionListener {
//declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr=0;
int currentCalculation;
//EventQueue invokeLater is used to ensure the run method is called in the dispatch thread of the EventQueue
//declaring the constructor for the class
public Calculator()
{
//instantiating guiCalculatorFrame
guiCalculatorFrame=new JFrame();
//the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
//setting the size of the frame
guiCalculatorFrame.setSize(400,400);
//The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
//JTextField is created to allow a set of characters to be entered
numberCalculator=new JTextArea();
//setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
//making the textfield not editable
numberCalculator.setEditable(false);
//container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
//panel is created and we will add buttons to the panel later in the program
buttonPanel=new JPanel();
//setting Layout to GridLayout to lay the components in a rectangular grid
buttonPanel.setLayout(new GridLayout(5,5));
//adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel,BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel,String.valueOf(i));
}
//next the five mathematical operators are added
addActionButton(buttonPanel,1,"+");
addActionButton(buttonPanel,2,"-");
addActionButton(buttonPanel,3,"*");
addActionButton(buttonPanel,4,"/");
addActionButton(buttonPanel,5,"^2");
addActionButton(buttonPanel,6,"C");
addActionButton(buttonPanel,7,"^");
addActionButton(buttonPanel,8,".");
//equalSign Button is created
JButton equalsSignButton=new JButton("=");
//the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
//checking if the numberCalculator field is a valid mathematical operator
{
if (!numberCalculator.getText().isEmpty())
{
//turning text into integer
int number=Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of operations
if (calculatorOpr==1)
{
int calculate=currentCalculation+number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==2)
{
int calculate=currentCalculation-number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==3)
{
int calculate=currentCalculation*number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==4)
{
int calculate=currentCalculation/number;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==5)
{
int calculate=currentCalculation*currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==6)
{
numberCalculator.setText("");
}
else if (calculatorOpr==7)
{
int calculate=(int) Math.sqrt(Integer.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
}
else if (calculatorOpr==8)
{
numberCalculator.append(".");
}
}
}
});
//adding equals sign to the panel
buttonPanel.add(equalsSignButton);
//setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
//passing two paremeters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne=new JButton(name);
//setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
//adding buttonOne to the container
contain.add(buttonOne);
}
//passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne=new JButton(text);
//setting the action command for the button created above
buttonOne.setActionCommand(text);
//creating a new class
Operators addAction=new Operators(i);
buttonOne.addActionListener(addAction);
//adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
//returning the command string associated with this string
String i=event.getActionCommand();
//setting the Text to the specified String
numberCalculator.setText(i);
}
//creating an inner class and implementing ActionListener
private class Operators implements ActionListener
{
private int operators;
//creating a constructor and passing a parameter
public Operators(int operation)
{
operators=operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalculation=Integer.parseInt(numberCalculator.getText());
calculatorOpr=operators;
}
}
}*
The problem was you were overwrting the text field. and the action listener for C button was wrong. This will solve your basic problems, but some work remaining. For instance you are not handling the . at the moment.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
// declaring some variables to be used in our program
JFrame guiCalculatorFrame;
JPanel buttonPanel;
JTextArea numberCalculator;
int calculatorOpr = 0;
int currentCalculation;
boolean isOperatorActive = false;
// EventQueue invokeLater is used to ensure the run method is called in the
// dispatch thread of the EventQueue
// declaring the constructor for the class
public Calculator() {
// instantiating guiCalculatorFrame
guiCalculatorFrame = new JFrame();
// the red cross sign drawn to exit the window
guiCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiCalculatorFrame.setTitle("Calculator");
// setting the size of the frame
guiCalculatorFrame.setSize(400, 400);
// The setLocationRelativeTo has been set to null to center the window
guiCalculatorFrame.setLocationRelativeTo(null);
// JTextField is created to allow a set of characters to be entered
numberCalculator = new JTextArea();
// setting the alignment of JTextField along the RIGHT axis
numberCalculator.setAlignmentX(JTextField.RIGHT);
// making the textfield not editable
numberCalculator.setEditable(false);
// container containing the components in the north region
guiCalculatorFrame.add(numberCalculator, BorderLayout.NORTH);
// panel is created and we will add buttons to the panel later in the
// program
buttonPanel = new JPanel();
// setting Layout to GridLayout to lay the components in a rectangular
// grid
buttonPanel.setLayout(new GridLayout(5, 5));
// adding the buttons to the frame. Putting the buttons in the center
guiCalculatorFrame.add(buttonPanel, BorderLayout.CENTER);
// a following for loop is done to add the numberButtons
for (int i = 0; i < 10; i++) {
addNumberButton(buttonPanel, String.valueOf(i));
}
// next the five mathematical operators are added
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
addActionButton(buttonPanel, 6, "C");
addActionButton(buttonPanel, 7, "^");
addActionButton(buttonPanel, 8, ".");
// equalSign Button is created
JButton equalsSignButton = new JButton("=");
// the action command for the equal sign button is set
equalsSignButton.setActionCommand("=");
equalsSignButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// checking if the numberCalculator field is a valid mathematical
// operator
isOperatorActive = true;
if (!numberCalculator.getText().isEmpty()) {
// turning text into integer
int number = Integer.parseInt(numberCalculator.getText());
// doing a series of if statements for the list of
// operations
int calculate = 0;
switch (calculatorOpr) {
case 1:
calculate = currentCalculation + number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 2:
calculate = currentCalculation - number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 3:
calculate = currentCalculation * number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 4:
calculate = currentCalculation / number;
numberCalculator.setText(Integer.toString(calculate));
break;
case 5:
calculate = currentCalculation * currentCalculation;
numberCalculator.setText(Integer.toString(calculate));
break;
case 7:
calculate = (int) Math.sqrt(Integer
.parseInt(numberCalculator.getText()));
numberCalculator.setText(Integer.toString(calculate));
break;
case 8:
numberCalculator.append(".");
break;
default:
break;
}
}
}
});
// adding equals sign to the panel
buttonPanel.add(equalsSignButton);
// setting the visibility to True so the frame can be seen
guiCalculatorFrame.setVisible(true);
}
// passing two parameters to the addNumberButton method
private void addNumberButton(Container contain, String name) {
JButton buttonOne = new JButton(name);
// setting the action command for the button created above
buttonOne.setActionCommand(name);
buttonOne.addActionListener(this);
// adding buttonOne to the container
contain.add(buttonOne);
}
// passing three parameters to the addActionButton method
private void addActionButton(Container contain, int i, String text) {
JButton buttonOne = new JButton(text);
// setting the action command for the button created above
buttonOne.setActionCommand(text);
// creating a new class
Operators addAction = new Operators(i);
buttonOne.addActionListener(addAction);
// adding buttonOne to the container
contain.add(buttonOne);
}
public void actionPerformed(ActionEvent event) {
// returning the command string associated with this string
String i = event.getActionCommand();
// setting the Text to the specified String
if(isOperatorActive){
numberCalculator.setText(i);
isOperatorActive = false;
} else {
numberCalculator.setText(numberCalculator.getText() + i);
}
}
// creating an inner class and implementing ActionListener
private class Operators implements ActionListener {
private int operators;
// creating a constructor and passing a parameter
public Operators(int operation) {
operators = operation;
}
public void actionPerformed(ActionEvent event) {
isOperatorActive = true;
switch (operators) {
case 6:
numberCalculator.setText("");
currentCalculation = 0;
calculatorOpr = 0;
break;
case 8:
isOperatorActive = false;
default:
currentCalculation = Integer.parseInt(numberCalculator.getText());
calculatorOpr = operators;
break;
}
}
}
}
import javax.swing.*;
import java.awt.*;
/*
# Author 12CSE54
# Date 29.10.14
*/
public class calculator1 extends JFrame
{
public calculator1() {
initComponents();
}
int a,b,c;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a+b;
jTextField3.setText(String.valueOf(c));
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a-b;
jTextField3.setText(String.valueOf(c));
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a*b;
jTextField3.setText(String.valueOf(c));
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
b=Integer.parseInt(jTextField2.getText());
c=a/b;
jTextField3.setText(String.valueOf(c));
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
public static void main(String ar[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new calculator1().setVisible(true);
}
});
}
I have a school assignment that i need to create. Below is the info:
Create a frame with ten buttons, labeled 0 through 9. To exit the program, the user must click on the correct three buttons in order, something like 7-3-5. If the wrong combination is used, the frame turns red.
I already finish the frame and the buttons with online research helps, but i just cant make the functionality to work. Please take a look at my codes and thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboNumber extends JFrame implements ActionListener{
//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;
//constructs the combolock object
public ComboNumber()
{
//sets flowlayout
getContentPane().setLayout(new FlowLayout());
Container c = getContentPane();
//creates buttons
button = new JButton[10];
for(int i = 0; i < button.length; ++i) {
button[i] = new JButton("" + i);
//adds buttons to the frame
c.add(button[i]);
//registers listeners with buttons
button[i].addActionListener(this);
}
//sets commands for the buttons (useless)
//sets title for frame
setTitle("ComboLock");
}
//end combolock object
//listener object
public void actionPerformed(ActionEvent evt)
{
Object o = evt.getSource();
for(int i = 0; i < button.length; ++i) {
if(button[i] == o) {
// it is button[i] that was cliked
// act accordingly
return;
}
}
}
//end listener object
//main method
public static void main (String[] args)
{
//calls object to format window
ComboNumber frm = new ComboNumber();
//WindowQuitter class to listen for window closing
WindowQuitter wQuit = new WindowQuitter();
frm.addWindowListener(wQuit);
//sets window size and visibility
frm.setSize(500, 500);
frm.setVisible(true);
}
//end main method
}
//end main class
//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
//exits the program when the window is closed
System.exit(0);
}
//end method
}
//end class
The basic idea is simple.
You need two things.
What the combination actually is
What the user has guessed
So. You need to add two variables. One contains the combination/secret, the other contains the guesses.
private String secret = "123";
private String guess = "";
This allows you to make the combination as long as you like ;)
Then in your actionPerformed method, you need to add the most recent button click to the guess, check it against the secret and see if they've made a good guess. If the length of the guess passes the number of characters in the secret, you need to reset the guess.
public void actionPerformed(ActionEvent evt) {
Object o = evt.getSource();
if (o instanceof JButton) {
JButton btn = (JButton) o;
guess += btn.getText();
if (guess.equals(secret)) {
JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
dispose();
} else if (guess.length() >= 3) {
JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
guess = "";
}
}
}
I just need to get it to alternate between "X" and "O" for the turns but it's only giving me X's.
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class tictactoe {
public static final int FRAME_WIDTH = 700;
public static final int FRAME_HEIGHT = 200;
public static void main(String[] args)
{
int slots = 9;
final JButton[] gameButton = new JButton[9];
JPanel ticTacToeBoard = new JPanel();
ticTacToeBoard.setLayout(new GridLayout(3, 3));
JButton clearButtons = new JButton("New Game");
for (int i = 0; i < slots; i++)
{
gameButton[i] = new JButton();
ticTacToeBoard.add(gameButton[i]);
final int countTurns = i;
gameButton[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object clicked = e.getSource();
int turns = 1;
for (int p = 0; p < 9; p++)
{
if(clicked == gameButton[countTurns] && turns < 10)
{
if (!(turns % 2 == 0))
{
((JButton)e.getSource()).setText("X");
turns++;
}
else
{
((JButton)e.getSource()).setText("O");
turns++;
}
}
}
}
});
final int integerHack = i;
clearButtons.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
gameButton[integerHack].setText("");
}
});
}
JButton exit = new JButton("Exit");
exit.setActionCommand("EXIT");
exit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd == "EXIT")
{
System.exit(FRAME_WIDTH);
}
}
});
JPanel rightPanel = new JPanel();
JLabel wonLabel = new JLabel();
rightPanel.setLayout(new GridLayout(1, 3));
rightPanel.add(wonLabel);
rightPanel.add(clearButtons);
rightPanel.add(exit);
JFrame mainFrame = new JFrame();
mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(1,2));
mainFrame.add(ticTacToeBoard);
mainFrame.add(rightPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Look at your actionPerformed method. Every time a click happens, you set turns to 1. As a result, !(turns % 2 == 0) will always evaluate true, and you'll always draw an X.
Just by quickly looking at your code, I would guess it is because your turn variable is local in all the ActionListener objects. Therefore, the turn variable is always 1 and you always run into the first if case. So the turn variable is always recreated on the stack as soon as you get a callback in the actionPerformed method. For a quick fix and test, try to put the turn variable in the tictactoe class and see if that helps.
The trouble is with the turns variable in your actionPerformed. If you want to keep a track of it you should move that out from your method.
Firstly, as the other people have also said, you want "turns" to be initialized outside all your loops.
Secondly, I would like to point out a typo:
if(clicked == gameButton[countTurns] && turns < 10)
should be
if(clicked == gameButton[p] && turns < 10)
...unless you really want to change each button's text from X to O nine times each time a button is clicked.
But even fixing that typo is pointless. Why loop through to find a specific button when it doesn't matter which specific button it is? All the buttons have the same action handler, anyway, just nine separate copies of it, because you are creating nine identical copies each time around.
Instead, because all the buttons do the same thing, you should have one action handler for all the buttons. If you're not sure how that's done, you create it outside your button making loop and assign it to a variable, and then you put in that variable when you assign each button's action handler, e.g.
gameButton[i].addActionListener(myActionListener);