Comparing arrays not working correctly? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Ok this is my code. Now I have it set up so far to display the correct pattern for 3 seconds, go to an input screen for the user to input, when the user clicks the screen 6 times it takes the pattern the user inputs and stores it into the array input, then checks if the input array and pattern array are the same. Now the problem is that when it checks for the arrays to be the same that it works correctly for the percent pattern but it doesn't work correctly for any other pattern.
How can I compare the two 2D arrays?
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InputGame implements Properties,Listeners{
public static JFrame gf = new JFrame();
public static JButton a1,a2,a3,a4;
public static JButton b1,b2,b3,b4;
public static JButton c1,c2,c3,c4;
public static JButton d1,d2,d3,d4;
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static int numOfClicks =0;
public static int numCorrect=0;
public static int[][] input = new int[][]{
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
//public static Thread d;
public static void clear()
{
gf.dispose();
}
public static void setup() {
gf.dispose();
gf = new JFrame();
gf.setLocation(300,100);
gf.setSize(size);
gf.setResizable(false);
gf.setLayout(Ggrid);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PatternGame.clear();
blank();
gf.setVisible(true);
System.out.print(numOfClicks);
}
public static void blank()
{
{
a1 = new JButton("");
a2 = new JButton("");
a3 = new JButton("");
a4 = new JButton("");
a1.addActionListener(new input());
a2.addActionListener(new input());
a3.addActionListener(new input());
a4.addActionListener(new input());
gf.add(a1);
gf.add(a2);
gf.add(a3);
gf.add(a4);
}
{
b1 = new JButton("");
b2 = new JButton("");
b3 = new JButton("");
b4 = new JButton("");
b1.addActionListener(new input());
b2.addActionListener(new input());
b3.addActionListener(new input());
b4.addActionListener(new input());
gf.add(b1);
gf.add(b2);
gf.add(b3);
gf.add(b4);
}
{
c1 = new JButton("");
c2 = new JButton("");
c3 = new JButton("");
c4 = new JButton("");
c1.addActionListener(new input());
c2.addActionListener(new input());
c3.addActionListener(new input());
c4.addActionListener(new input());
gf.add(c1);
gf.add(c2);
gf.add(c3);
gf.add(c4);
}
{
d1 = new JButton("");
d2 = new JButton("");
d3 = new JButton("");
d4 = new JButton("");
d1.addActionListener(new input());
d2.addActionListener(new input());
d3.addActionListener(new input());
d4.addActionListener(new input());
gf.add(d1);
gf.add(d2);
gf.add(d3);
gf.add(d4);
}
}
public static void input()
{
{
String x = a1.getText();
if (x.equals("X"))
{
input[0][0] = 1;
}
x = a2.getText();
if (x.equals("X"))
{
input[0][1] = 1;
}
x = a3.getText();
if (x.equals("X"))
{
input[0][2] = 1;
}
x = a4.getText();
if (x.equals("X"))
{
input[0][3] = 1;
}
}
{
String x = b1.getText();
if (x.equals("X"))
{
input[1][0] = 1;
}
x = b2.getText();
if (x.equals("X"))
{
input[1][1] = 1;
}
x = b3.getText();
if (x.equals("X"))
{
input[1][2] = 1;
}
x = b4.getText();
if (x.equals("X"))
{
input[1][3] = 1;
}
}
{
String x = c1.getText();
if (x.equals("X"))
{
input[2][0] = 1;
}
x = c2.getText();
if (x.equals("X"))
{
input[2][1] = 1;
}
x = c3.getText();
if (x.equals("X"))
{
input[2][2] = 1;
}
x = c4.getText();
if (x.equals("X"))
{
input[2][3] = 1;
}
}
{
String x = d1.getText();
if (x.equals("X"))
{
input[3][0] = 1;
}
x = d2.getText();
if (x.equals("X"))
{
input[3][1] = 1;
}
x = d3.getText();
if (x.equals("X"))
{
input[3][2] = 1;
}
x = d4.getText();
if (x.equals("X"))
{
input[3][3] = 1;
}
}
}
public static boolean checkCorrect()
{
input();
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (order == 1)
{
if (handlebars[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 2)
{
if (ys[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 3)
{
if (spaceShip[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 4)
{
if (flock[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 5)
{
if (percent[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
if (order == 6)
{
if (square[a][b] == input[a][b])
{
InputGame.numCorrect++;
}
}
}
}
System.out.println(numCorrect);
for (int a =0;a<4;a++)
{
System.out.println();
for(int b=0;b<4;b++)
{
System.out.print(input[a][b]);
}
}
for (int a =0;a<4;a++)
{
System.out.println();
for(int b=0;b<4;b++)
{
System.out.print(ys[a][b]);
}
}
if (numCorrect == 16)
{
return true;
}
else
{
return false;
}
}
}
package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public interface Listeners
{
static PatternGame game = new PatternGame();
InputGame game2 = new InputGame();
static class inst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("inst".equals(e.getActionCommand()))
{
}
}
}
static class play implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("play".equals(e.getActionCommand()))
{
menu.mf.dispose();
PatternGame.gameStart();
}
}
}
static class exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("exit".equals(e.getActionCommand()))
{
System.exit(0);
}
}
}
static class input implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (InputGame.numOfClicks !=1)
{
JButton x = (JButton) e.getSource();
x.setText("X");
InputGame.numOfClicks--;
}
else if (InputGame.numOfClicks ==1)
{
JButton x = (JButton) e.getSource();
x.setText("X");
InputGame.numOfClicks--;
if (InputGame.checkCorrect())
{
int yesno = JOptionPane.showConfirmDialog(null, "<html> Correct!" +"<br>Would you like another pattern?");
if (yesno == JOptionPane.YES_OPTION)
{
PatternGame.order++;
InputGame.clear();
PatternGame.gameStart();
}
else
{
InputGame.clear();
menu.start();
}
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect!");
InputGame.clear();
menu.start();
}
}
}
}
}
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PatternGame implements Properties
{
public static JFrame df = new JFrame();
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static void DisplayPat()
{
df.dispose();
df = new JFrame();
df.setLocation(300,100);
df.setSize(size);
df.setResizable(false);
df.setLayout(Ggrid);
df.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
df.setVisible(true);
}
public static boolean StayIn = true;
public static InputGame game = new InputGame();
public static int flag =0;
public static void clear()
{
df.dispose();
}
public static void gameStart()
{
DisplayPat();
getpattern();
schedule(3);
//notifyAll();
}
public static void blank()
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
JButton button = new JButton(" ");
df.add(button);
}
}
}
public static void getpattern()
{
InputGame.numOfClicks=0;
if (order == 1)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (handlebars[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
flag =1;
}
}
}
if (order == 2)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (ys[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
if (order == 3)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (spaceShip[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
} if (order == 4)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (flock[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
} if (order == 5)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (percent[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
if (order == 6)
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (square[a][b] == 1)
{
JButton button = new JButton("X");
df.add(button);
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
df.add(button);
}
}
}
}
df.setVisible(true);
}
public static Timer timer = new Timer(); //timer object
public static void schedule(int seconds) {
timer.schedule(new ScheduleTask(), seconds*1000);
}
static class ScheduleTask extends TimerTask {
public void run() {
InputGame.setup();
// timer.cancel(); //Terminate Timer thread
}
}
}
package game;
public interface Properties
{
int[][] percent = new int[][]{
{1,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,1}
};
int[][] spaceShip = new int[][]{
{0,1,1,0},
{0,0,0,0},
{0,1,1,0},
{1,0,0,1}
};
int[][] flock = new int[][]{
{0,0,0,0},
{1,0,1,0},
{0,1,0,1},
{1,0,1,0}
};
int[][] ys = new int[][]{
{0,0,1,0},
{1,0,1,0},
{0,1,0,1},
{0,1,0,0}
};
int[][] handlebars = new int[][]{
{1,0,0,0},
{0,1,1,0},
{0,1,1,0},
{0,0,0,1}
};
int[][] square = new int[][]{
{0,1,0,1},
{1,0,0,0},
{0,0,0,1},
{1,0,1,0}
};
}

Try using:
Arrays.equals(); // <---- One Dimensional Arrays
or
ArrayUtils.isEquals(); // <---- Multi Dimensional Arrays
These methods will compare the actual contents of the two arrays (not if they are the same reference or same object) and you wont have to step through each element individually.
Hope it helps!

Related

Why wont my simon game work and what do i need to do so it works

Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}

Why is JApplet showing a blank gray screen?

So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.

Hello I am creating a TicTacToe game for myself to understand Java better

however I am not sure where I am supposed to enter the whoWins() method. Do I enter this method in the actionperformed Method of the buttons or do i need to something different. Please help.
public class TTT extends JFrame implements ActionListener {
private JButton buttons[] = new JButton[9];
private JButton exitButton;
public JLabel title;
public JPanel titlePanel, panel;
private int count = 0;
int symbolCount = 0;
private boolean win = false;
public TTT() {
title = new JLabel("Welcome to my Tic Tac Toe Game!");
titlePanel = new JPanel();
title.setFont(new Font(Font.SERIF, 0, 30));
titlePanel.add(title);
this.add(titlePanel, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
panel.add(buttons[i]);
buttons[i].setEnabled(true);
buttons[i].addActionListener(this);
}
this.add(panel, BorderLayout.CENTER);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
exitButton = new JButton("Quit");
panel1.add(exitButton);
this.add(panel1, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(WIDTH);
}
});
}
public void whoWins() {
//Determines who wins using for the horizontal rows.
if (buttons[0].getText() == buttons[1].getText() && buttons[1].getText() == buttons[2].getText() && buttons[0].getText() != "") {
win = true;
} else if (buttons[3].getText() == buttons[4].getText() && buttons[4].getText() == buttons[5].getText() && buttons[3].getText() != "") {
win = true;
} else if (buttons[6].getText() == buttons[7].getText() && buttons[7].getText() == buttons[8].getText() && buttons[6].getText() != "") {
win = true;
} //Determines the verticles wins
else if (buttons[0].getText() == buttons[3].getText() && buttons[3].getText() == buttons[6].getText() && buttons[0].getText() != "") {
win = true;
} else if (buttons[1].getText() == buttons[4].getText() && buttons[4].getText() == buttons[7].getText() && buttons[1].getText() != "") {
win = true;
} else if (buttons[2].getText() == buttons[5].getText() && buttons[5].getText() == buttons[8].getText() && buttons[2].getText() != "") {
win = true;
}
// Diagnol Wins
else if (buttons[0].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[8].getText()&& buttons[0].getText()!= "") {
win = true;
}else if (buttons[2].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[6].getText()&& buttons[1].getText()!= "") {
win = true;
}else {
win = false;
}
//who won
if (win = true) {
JOptionPane.showMessageDialog(null, "wins");
}else if (count == 9 && win == false) {
JOptionPane.showMessageDialog(null, "Tie game");
}
}
public static void main(String[] args) {
TTT ref1 = new TTT();
ref1.setTitle("Tic Tac Toe");
ref1.setVisible(true);
ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ref1.setSize(500, 500);
ref1.setLocationRelativeTo(null);
// ref1.whoWins();
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
for (JButton button : buttons) {
if (button == e.getSource()) {
if (symbolCount % 2 == 0) {
button.setText("X");
button.setEnabled(false);
} else {
button.setText("O");
button.setEnabled(false);
}
}
}
if (count >= buttons.length) {
JOptionPane.showMessageDialog(null, "End");
}
symbolCount++;
}
}
If you really want to do this right, then I suggest making some big changes, some M-V-C type changes:
First and foremost, separate out the logic of the game from the game GUI. This would mean that the code that determines who wins should not be in any code that contains GUI type code. This will be your "model"
Next you should never have GUI code implement listener interfaces, so try to get that out of the GUI and possibly have it go into its own class, the "Control" class.
Finally the GUI or "View" class will concern itself with displaying the model's state and getting input from the user and transmitting this input to the control.
For example,...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.EnumMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
public class TicTacToeMain {
private static void createAndShowGui() {
TttView view = null;
try {
view = new TttView();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
TttModel model = new TttModel();
new TttControl(model, view);
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(view.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum TttPiece {
EMPTY, X, O
}
class TttView {
public static final String IMAGE = "/imgFolder/TicTacToe.png";
private static final int GAP = 5;
private JPanel mainPanel = new JPanel();
private JPanel tttPanel = new JPanel();
private Map<TttPiece, Icon> iconMap = new EnumMap<>(TttPiece.class);
private JLabel[][] grid = new JLabel[TttModel.ROWS][TttModel.COLS];
private TttControl control;
public TttView() throws IOException {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(IMAGE));
Icon[] imgIcons = splitImg(img);
iconMap.put(TttPiece.X, imgIcons[0]);
iconMap.put(TttPiece.O, imgIcons[1]);
iconMap.put(TttPiece.EMPTY, createEmptyIcon(imgIcons[0]));
tttPanel.setLayout(new GridLayout(grid.length, grid[0].length, GAP, GAP));
tttPanel.setBackground(Color.black);
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = new JLabel(iconMap.get(TttPiece.EMPTY));
grid[row][col].setOpaque(true);
grid[row][col].setBackground(Color.LIGHT_GRAY);
grid[row][col].addMouseListener(mouseAdapter);
tttPanel.add(grid[row][col]);
}
}
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton(new ClearAction("Clear", KeyEvent.VK_C)));
btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
int blGap = 2;
mainPanel.setLayout(new BorderLayout(blGap, blGap));
mainPanel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap,
blGap));
mainPanel.add(tttPanel, BorderLayout.CENTER);
mainPanel.add(btnPanel, BorderLayout.SOUTH);
}
public void setControl(TttControl control) {
this.control = control;
}
public JComponent getMainPanel() {
return mainPanel;
}
private Icon createEmptyIcon(Icon icon) {
int width = icon.getIconWidth();
int height = icon.getIconHeight();
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
return new ImageIcon(img);
}
private Icon[] splitImg(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
int gap = 5;
Icon[] icons = new ImageIcon[2];
icons[0] = new ImageIcon(img.getSubimage(0, 0, w / 2 - gap, h / 2 - gap));
icons[1] = new ImageIcon(img.getSubimage(w / 2 + gap, 0, w / 2 - gap, h
/ 2 - gap));
return icons;
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if (control == null) {
return;
}
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
if (grid[row][col] == e.getSource()) {
control.gridPress(row, col);
}
}
}
}
}
private class ClearAction extends AbstractAction {
public ClearAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (control != null) {
control.clear();
}
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (control != null) {
control.exit(evt);
}
}
}
public void setGridIcon(int row, int col, TttPiece tttPiece) {
grid[row][col].setIcon(iconMap.get(tttPiece));
}
}
class TttControl {
private TttModel model;
private TttView view;
public TttControl(TttModel model, TttView view) {
this.model = model;
this.view = view;
view.setControl(this);
model.addPropertyChangeListener(new ModelListener());
}
public void exit(ActionEvent evt) {
Window win = SwingUtilities
.getWindowAncestor((Component) evt.getSource());
win.dispose();
}
public void gridPress(int row, int col) {
try {
model.gridPress(row, col);
} catch (TttException e) {
// TODO: notify user
// e.printStackTrace();
}
}
public void clear() {
model.clear();
}
private class ModelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (TttModel.GRID_POSITION.equals(evt.getPropertyName())) {
TttPiece[][] tttGrid = model.getTttGrid();
for (int row = 0; row < tttGrid.length; row++) {
for (int col = 0; col < tttGrid[row].length; col++) {
view.setGridIcon(row, col, tttGrid[row][col]);
}
}
}
}
}
}
class TttModel {
public static final int ROWS = 3;
public static final int COLS = ROWS;
public static final String GRID_POSITION = "grid position";
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
private TttPiece[][] tttGrid = new TttPiece[ROWS][COLS];
private TttPiece player = TttPiece.X;
private boolean gameOver;
public TttModel() {
clear();
}
public void setGridPosition(int row, int col, TttPiece piece)
throws TttException {
if (gameOver) {
return;
}
if (tttGrid[row][col] == TttPiece.EMPTY) {
tttGrid[row][col] = piece;
checkForWin(row, col, piece);
nextPlayer();
pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid);
} else {
String message = "Invalid setGridPosition for row: %d, col: %d, piece: %s. "
+ "Spot already occupied by piece: %s";
message = String.format(message, row, col, piece, tttGrid[row][col]);
throw new TttException(message);
}
}
public TttPiece[][] getTttGrid() {
return tttGrid;
}
public void gridPress(int row, int col) throws TttException {
setGridPosition(row, col, player);
}
public void nextPlayer() {
player = player == TttPiece.X ? TttPiece.O : TttPiece.X;
}
private void checkForWin(int row, int col, TttPiece piece) {
// TODO finish
}
public void clear() {
for (int row = 0; row < tttGrid.length; row++) {
for (int col = 0; col < tttGrid[row].length; col++) {
tttGrid[row][col] = TttPiece.EMPTY;
}
}
player = TttPiece.X;
pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
}
#SuppressWarnings("serial")
class TttException extends Exception {
public TttException() {
super();
}
public TttException(String message) {
super(message);
}
}
Using for my images:
With GUI looking like:
I am also interested in writing a Tic Tac Toe game, so I copied your code, and did a little modification, and it passed test, check following:
package eric.j2se.swing;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
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.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* <p>
* Simple game of Tic Tac Toe.
* </p>
*
* #author eric
* #date Apr 16, 2014 11:03:48 AM
*/
#SuppressWarnings("serial")
public class TicTacToe extends JFrame implements ActionListener {
// 2 players
public static final char playerX = 'X';
public static final char playerO = 'O';
// null player
public static final char playerN = 'N';
// the winer, init to null player
private Character winner = playerN;
// indicate whether game over
private boolean gameOver = false;
// count of button used,
private int count = 0;
private Character buttonPlayers[] = new Character[9];
private JButton buttons[] = new JButton[9];
private JButton exitButton;
public JLabel title;
public JPanel titlePanel, panel;
public TicTacToe() {
// init buttonPlayers
for (int i = 0; i < 9; i++) {
buttonPlayers[i] = playerN;
}
// init title
title = new JLabel("Welcome to Tic Tac Toe!");
titlePanel = new JPanel();
title.setFont(new Font(Font.SERIF, 0, 30));
titlePanel.add(title);
this.add(titlePanel, BorderLayout.NORTH);
// init 9 button
panel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton();
panel.add(buttons[i]);
buttons[i].setEnabled(true);
buttons[i].addActionListener(this);
}
// init exit button
this.add(panel, BorderLayout.CENTER);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
exitButton = new JButton("Quit");
panel1.add(exitButton);
this.add(panel1, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(WIDTH);
}
});
}
public void whoWins() {
// determine winner - horizontal rows
if (!gameOver) {
for (int i = 0; i < 3; i++) {
if ((buttonPlayers[0 + i * 3] != playerN) && (buttonPlayers[0 + i * 3].equals(buttonPlayers[1 + i * 3]))
&& buttonPlayers[1 + i * 3].equals(buttonPlayers[2 + i * 3])) {
winner = buttonPlayers[0 + i * 3];
gameOver = true;
break;
}
}
}
// determine winner - vertical rows
if (!gameOver) {
for (int i = 0; i < 3; i++) {
if ((buttonPlayers[i + 0 * 3] != playerN) && (buttonPlayers[i + 0 * 3].equals(buttonPlayers[i + 1 * 3]))
&& buttonPlayers[i + 1 * 3].equals(buttonPlayers[i + 2 * 3])) {
winner = buttonPlayers[i + 0 * 3];
gameOver = true;
break;
}
}
}
// determine winner - diagonal rows
if (!gameOver) {
int winButtonIndex = -1;
if ((buttonPlayers[0] != playerN) && (buttonPlayers[0].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[8])) {
winButtonIndex = 0;
} else if ((buttonPlayers[2] != playerN) && (buttonPlayers[2].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[6])) {
winButtonIndex = 2;
}
if (winButtonIndex >= 0) {
winner = buttonPlayers[winButtonIndex];
gameOver = true;
}
}
// full
if (count == 9) {
gameOver = true;
}
if (gameOver) {
String tip = "";
switch (winner) {
case playerO:
tip = "Player O win!";
break;
case playerX:
tip = "Player X win!";
break;
default:
tip = "Draw game!";
break;
}
JOptionPane.showMessageDialog(null, tip);
}
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
JButton button = buttons[i];
if (button == e.getSource()) {
Character currentPlayer = (count % 2 == 1 ? playerX : playerO);
button.setText(String.valueOf(currentPlayer));
buttonPlayers[i] = currentPlayer;
button.setEnabled(false);
break;
}
}
count++;
whoWins();
}
public static void main(String[] args) {
TicTacToe ref1 = new TicTacToe();
ref1.setTitle("Tic Tac Toe");
ref1.setVisible(true);
ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ref1.setSize(500, 500);
ref1.setLocationRelativeTo(null);
}
}
about when to call the win check:
check each time you click 1 of the 9 buttons,
about the flag:
I use 2 flag instead of 1 flag to indicate game over & winner, because in TTT game, draw game is very usual, after play several times, you always get draw game ...
a little suggestion to your code:
when compare string, use equals(), not ==,
define const values in variable, not write it in logic, e.g. 'O' 'X',
don't repeat code, try use logic control to make it short & easy to read & easy to maintain,

How can I get the source of the button and get this to work?

package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public interface Listeners
{
static PatternGame game = new PatternGame();
InputGame game2 = new InputGame();
static class inst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("inst".equals(e.getActionCommand()))
{
}
}
}
static class play implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("play".equals(e.getActionCommand()))
{
menu.mf.dispose();
PatternGame.gameStart();
}
}
}
static class exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ("exit".equals(e.getActionCommand()))
{
System.exit(0);
}
}
}
static class input implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (InputGame.numOfClicks != 0)
{
InputGame.button = (JButton) e.getSource();
InputGame.button.setText("X");
InputGame.numOfClicks--;
}
else
{
if (InputGame.checkCorrect())
{
JOptionPane.showConfirmDialog(null, "Would you like another pattern?");
PatternGame.order++;
PatternGame.gameStart();
}
else
{
JOptionPane.showMessageDialog(null, "Incorrect!");
menu.start();
}
}
}
}
}
package game;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InputGame implements Properties,Listeners{
public static JFrame gf = new JFrame();
public static JButton button = new JButton();
public static int height = 800;
public static int width = 600;
public static int gsize = 4;
public static int order =1;
public static Dimension size = new Dimension(height,width);
public static menu Menu = new menu();
public static GridLayout Ggrid = new GridLayout(gsize,gsize);
public static int numOfClicks =0;
public static int numCorrect=0;
public static int[][] input = new int[][]{
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
//public static Thread d;
public static void setup() {
gf.dispose();
gf = new JFrame();
gf.setLocation(300,100);
gf.setSize(size);
gf.setResizable(false);
gf.setLayout(Ggrid);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PatternGame.clear();
blank();
gf.setVisible(true);
System.out.print(numOfClicks);
}
public static void blank()
{
for (int a =0;a<4;a++)
{
for (int b =0;b<4;b++)
{
button = new JButton("");
button.setActionCommand("");
button.addActionListener(new input());
gf.add(button);
}
}
}
public static void input()
{
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
String x = button.getText();
if (x.equals("X"))
{
input[a][b] = 1;
}
else if (x.equals(""))
{
input[a][b] = 0;
}
System.out.println(input[a][b]);
}
}
}
public static boolean checkCorrect()
{
input();
for (int a=0;a<4;a++)
{
for(int b=0;b<4;b++)
{
if (order == 1)
{
if (handlebars[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 2)
{
if (ys[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 3)
{
if (spaceShip[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 4)
{
if (flock[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 5)
{
if (percent[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
if (order == 6)
{
if (square[a][b] == 1)
{
JButton button = new JButton("X");
InputGame.numOfClicks++;
}
else
{
JButton button = new JButton("");
}
}
}
}
return false;
}
}
Ok, this is my code. Now what I want the program to accomplish is for the program to display the blank screen(which I have done) then when the user clicks one of the buttons and it places a X on that button. Then after 6 clicks for the program to translate the pattern they put in to the input array, so I can compare the input array to the pattern array, and be able to tell the user if its correct or not and move on. What this program does now is it displays the blank screen then when a button is pressed it displays the X. I got it to check for one button but I don't know how to check for all of them. So how could I check each button for the text it holds.
You can call getComponents() on the parent container- whether panel, frame or window and then check if it is an instance of button, then check the text set on it like this:
Component[] comps = parent.getComponents();
for(Component c:comps){
if(c instanceof JButton){
JButton btn = (JButton) c;
String text = btn.getText();
//Use text for whatever, add it to an array or something
}
}
Hope you get the idea

JPanel elements are not appearing

I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}
JFrame zaWindow..
This should be a modal dialog or a JOptionPane. E.G. This country has 3 states, each with 10 postcodes.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;
class ZipQuery {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);
JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ZipNumberModel extends SpinnerNumberModel {
private ArrayList<Integer> zipCodes;
private int index = 0;
ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}
#Override
public Object getValue() {
return zipCodes.get(index);
}
#Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}
#Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}

Categories