How do I implement a reset button for my GUI? - java

I am an AP Computer Science student and I need help with my assignment for the class. My assignment is to create a simple GUI or game using Eclipse. I made a simple player vs. player tic-tac-toe game, but I do not know how to create a "reset" button for my GUI. I tried multiple times, but I can't get it to work or show up in my GUI. I would appreciate some pointers on how to implement a functional reset button, so I would not have exit out of my GUI multiple times to start playing again. Here is the code I have written so far.
package gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToeGUI implements ActionListener
{
JFrame window = new JFrame("Tic-Tac-Toe");
JButton[] button;
JButton reset = new JButton("Reset");
String letter = "";
public int count = 0;
public boolean win = false;
public TicTacToeGUI()
{
button = new JButton[9];
window.setSize(300,300);
window.setLayout(new GridLayout(3,3));
JButton dummy = new JButton("");
Font font = dummy.getFont();
Font bigFont = font.deriveFont(font.getSize2D() * 5.0f);
JButton reset = new JButton("Reset");
for(int i = 0; i < 9; i++)
{
button[i] = new JButton("");
button[i].setFont(bigFont);
button[i].addActionListener(this);
window.add(button[i]);
}
window.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
count++;
if(count % 2 == 1)
{
letter = "X";
}
else
{
letter = "O";
}
Object but = a.getSource();
for(int i = 0; i < 9; i++)
{
if(but == button[i])
{
button[i].setText(letter);
button[i].setEnabled(false);
break;
}
}
if( button[0].getText() == button[1].getText() && button[1].getText() == button[2].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[3].getText() == button[4].getText() && button[4].getText() == button[5].getText() && button[3].getText() != "")
{
win = true;
}
else if(button[6].getText() == button[7].getText() && button[7].getText() == button[8].getText() && button[6].getText() != "")
{
win = true;
}
else if(button[0].getText() == button[3].getText() && button[3].getText() == button[6].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[1].getText() == button[4].getText() && button[4].getText() == button[7].getText() && button[1].getText() != "")
{
win = true;
}
else if(button[2].getText() == button[5].getText() && button[5].getText() == button[8].getText() && button[2].getText() != "")
{
win = true;
}
else if(button[0].getText() == button[4].getText() && button[4].getText() == button[8].getText() && button[0].getText() != "")
{
win = true;
}
else if(button[2].getText() == button[4].getText() && button[4].getText() == button[6].getText() && button[2].getText() != "")
{
win = true;
}
else
{
win = false;
}
if(win == true)
{
JOptionPane.showMessageDialog(null, letter + " WINS!");
}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game!");
}
}
public static void main(String[] args)
{
new TicTacToeGUI();
}
}

You might want to try this:
window.setLayout(new BorderLayout());
JPanel panel = new JPanel( new GridLayout(3, 3));
window.add(panel, BorderLayout.CENTER); // add panel to window center
window.add(reset, BorderLayout.SOUTH); // add reset button to window bottom
Of course, you will have to add your 9 buttons to panel now, not to window.
But why don't you just reset automatically after the user confirmed the dialog at the end of the game?

Reset your board after a tie or win. An example reset method. Otherwise you are going to have to make room on your Frame to hold a button to do this.
private void ResetBoard() {
for(int i = 0; i < 9; i++) {
button[i].setText("");
button[i].setEnabled(true);
count = 0;
}
}
Then use this method when a check is made to see if a player won or the game ends in a tie as below:
if(win == true)
{
JOptionPane.showMessageDialog(null, letter + " WINS!");
ResetBoard();
}
else if(count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game!");
ResetBoard();
}

Related

Java GUI Freezes Tic-Tac-Toe

I have written Tic-Tac-Toe in Java. The issue I seem to be having is when there is a tie between the (human)player 1 and the (computer) player 2, the GUI freezes. I have created a tieCheck in both the "Buttonlistener" Class and the "Methods" to catch a tie.
The way my program works is that when a button is pressed, it passes a value to the array in the methods class. in this array, 1 = player 1, and 2 = player 2.
The human player always goes first, so when the human player has gone 4 times, I check for a tie before the last turn is taken with tieCheck(turncount); this method then utilizes the tieCheck() in the methods class which will place a 1 in the last place and then checks for a winner. if no winner is found, it returns true. then the tieCheck() from the ButtonListener class will disable all the buttons, and say "it is a tie". However, none of this is working. The program will still allow me to make the last move and will result in a frozen window I have to close using task manager. please help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MediumPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JButton playAgain;
private JButton[] buttons = new JButton[9];
private JLabel label, turn;
public MediumPanel() {
ButtonListener listener = new ButtonListener();
Font f1 = new Font("Arial", Font.BOLD , 100);
Font f2 = new Font("Arial", Font.PLAIN, 50);
JPanel ButtonPanel = new JPanel();
ButtonPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i <= 8; i++) {
buttons[i] = new JButton("");
buttons[i].addActionListener(listener);
buttons[i].setBackground(Color.white);
buttons[i].setFont(f1);
ButtonPanel.add(buttons[i]);
}
playAgain = new JButton();
label = new JLabel();
label.setFont(f2);
turn = new JLabel("");
turn.setFont(f1);
playAgain.addActionListener(listener);
playAgain.setText("Click to Play Again");
playAgain.setFont(f2);
setBackground(Color.green);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 500));
add(playAgain, BorderLayout.SOUTH);
add(label, BorderLayout.NORTH);
add(ButtonPanel);
}
private class ButtonListener implements ActionListener {
Methods method = new Methods();
public void reset() {
label.setText("");
for (int i = 0; i <= 8; i++) {
buttons[i].setEnabled(true);
buttons[i].setText("");
}
method.reset();
}
// inserts
public void insertG(int num) {
for (int i = 0; i <= 8; i++) {
if (num == i) {
buttons[i].setText("O");
buttons[i].setEnabled(false);
}
}
}
public void disable() {
for(int i=0; i<=8; i++) {
buttons[i].setEnabled(false);
}
}
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
disable();
label.setText("It's a tie!");
}
}
// Checks for buttons being pressed
public void actionPerformed(ActionEvent event) {
int turncount = 0;
//Resets array board, GUI buttons, and label when clicked
if (event.getSource() == playAgain) {
reset();
}
// Button 0
if (event.getSource() == buttons[0]) {
buttons[0].setText("X");
buttons[0].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(0, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 1
if (event.getSource() == buttons[1]) {
buttons[1].setText("X");
buttons[1].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(1, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 2
if (event.getSource() == buttons[2]) {
buttons[2].setText("X");
buttons[2].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(2, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 3
if (event.getSource() == buttons[3]) {
buttons[3].setText("X");
buttons[3].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(3, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 4
if (event.getSource() == buttons[4]) {
buttons[4].setText("X");
buttons[4].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(4, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 5
if (event.getSource() == buttons[5]) {
buttons[5].setText("X");
buttons[5].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(5, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
//Button 6
if (event.getSource() == buttons[6]) {
buttons[6].setText("X");
buttons[6].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(6, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// Button 7
if (event.getSource() == buttons[7]) {
buttons[7].setText("X");
buttons[7].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(7, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
//Button 8
if (event.getSource() == buttons[8]) {
buttons[8].setText("X");
buttons[8].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(8, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else {
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
}
}
}
import java.util.*;
public class Methods {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
// represents Tick-Tack-Toe Play Field
int[] board = new int[9];
// resets board array
public void reset() {
for (int i = 0; i < 9; i++) {
board[i] = 0;
}
}
// inserts player on a specific spot
public void insertArray(int spot, int player) {
board[spot] = player;
}
// for hard mode
public void expertMove(int player1, int player2) {
}
// for medium
public int smartMove(int player1, int player2) {
boolean turntaken = false;
for (int i = 0; i < 9; i++) {
if (board[i] == 0) {
board[i] = player2;
if (winCheck(player2) == 1) {
return i;
} else {
board[i] = 0;
}
}
}
for (int i = 0; i < 9; i++) {
if (board[i] == 0) {
board[i] = player1;
if (winCheck(player1) != 1) {
board[i] = 0;
} else {
board[i] = player2;
return i;
}
}
}
// If the opposite player is not about to win, then Computer goes randomly
if (turntaken == false) {
return randomMove(player2);
}
return 0;
}
// For easy mode and also utilized in smartMove() for medium mode
public int randomMove(int player) {
int rnum = 0;
rnum = rand.nextInt(8);
while (emptyCheck(rnum) != true) {
rnum = rand.nextInt(8);
}
board[rnum] = player;
return rnum;
}
//Returns 1 if player won the game
public int winCheck(int player) {
for (int ii = 0; ii <= 2; ii++) {
if (board[ii] == player && board[ii + 3] == player && board[ii + 6] == player)
return 1;
}
for (int z = 0; z <= 6; z = z + 3) {
if (board[z] == player && board[z + 1] == player && board[z + 2] == player)
return 1;
}
if (board[0] == player && board[4] == player && board[8] == player) {
return 1;
}
if (board[2] == player && board[4] == player && board[6] == player) {
return 1;
}
return 0;
}
//Returns true if tie
public boolean tieCheck() {
for(int i=0;i < 9; i++) {
if(board[i] == 0) {
board[i] = 2;
if(winCheck(1) != 1 && winCheck(2) != 1) {
return true;
}else {
board[i] = 0;
}
}
}
return false;
}
// Checks if empty: True if empty/false if taken by player
public boolean emptyCheck(int rnum) {
if (board[rnum] == 0) {
return true;
} else {
return false;
}
}
}
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class Driver {
public static void main(String []args) {
JTabbedPane difficulty = new JTabbedPane();
//difficulty.addTab("Easy", new EasyPanel());
difficulty.addTab("Medium", new MediumPanel());
//difficulty.addTab("Hard", new HardPanel());
Font f = new Font("Arial", Font.PLAIN, 20);
difficulty.setFont(f);
JFrame frame = new JFrame("Tic-Tac-Toe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(difficulty);
frame.pack();
frame.setVisible(true);
}
On every click, you set turncount = 0:
// Checks for buttons being pressed
public void actionPerformed(ActionEvent event) {
int turncount = 0;
but in your method tieCheck:
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
disable();
label.setText("It's a tie!");
}
}
you check if turncount == 4but it is always 1. You should change the turncount variable from local to global.
And then in method randomMove, you have an endless loop:
// For easy mode and also utilized in smartMove() for medium mode
public int randomMove(int player) {
int rnum = 0;
rnum = rand.nextInt(8);
while (emptyCheck(rnum) != true) { // <--------- HERE
rnum = rand.nextInt(8);
}
Like Peter1982 said in his answer, you should make turncount a class variable instead of a method variable so that it doesn't get reset every time you call the actionPerformed method.
To stop the game from getting frozen, you can create a boolean class variable that keeps track of if the game is over, such as gameOver. You then update gameOver in the tieCheck method, for example:
private class ButtonListener implements ActionListener {
boolean gameOver = false;
// ...
// Checks array using tieCheck from Methods class for a tie
public void tieCheck(int turncount) {
if (turncount == 4 && method.tieCheck() == true) {
gameOver = true; // <---- Update gameOver
disable();
label.setText("It's a tie!");
}
}
// Button 0
if (event.getSource() == buttons[0]) {
buttons[0].setText("X");
buttons[0].setEnabled(false);
turncount++;
tieCheck(turncount);
method.insertArray(0, 1);
if (method.winCheck(1) == 1) {
label.setText("You Won!");
disable();
} else if (!gameOver) { // <---- Check if the game is over
insertG(method.smartMove(1, 2));
if (method.winCheck(2) == 1) {
label.setText("You Lost!");
disable();
}
}
}
// ...
}
Make sure to reset turncount and tieCheck in your reset method.
Also, as an extra note, when I was looking through your code, I noticed that in your randomMove method you have the following: rnum = rand.nextInt(8);. Currently, this won't allow the computer to make a random move on the 9th button because rand.nextInt(8) will return a value of 0 through 7. This is because the 8 is exclusive. So just put 9 as the parameter like this: rand.nextInt(9) to get 0 through 8. I know it is trivial but I just wanted to point it out.

Implementing a game menu in processing3

I am making a little game for my university coursework and got stuck at the menu creation. Been trying to solve this for a while. Here goes the code:
Before trying to fiddle around the loop and noLoop() functions and before I moved the arrow placement from void setup to void keypressed my game has worked. Now the program freezes before running draw.
What I want is to only display the menu background before the key, in this case s for start, has been pressed. If anyone could come up with some directions it would be of a great help.
Thanks in advance.
int totalArrows = 6;
arrowclass[] theArrows = new arrowclass[totalArrows];
PImage[] imgList = new PImage[4];
PImage bg;
PImage life;
PImage menu;
int score;
int loose = 3;
void setup() {
size(400, 600);
bg = loadImage("bck.jpg");
life = loadImage("life.png");
menu = loadImage("menu.jpg");
background(menu);
// loading the arrow imgs
for (int i= 0; i<4; i++) {
println(i+".png");
imgList[i] = loadImage(i+".png");
}
noLoop();
}
void draw() {
textSize(32);
text(score,30,100);
// active area
fill(255,31,31);
rect(0,500,width,100);
//lifetrack
if (loose==3){
image(life,10,10);
image(life,45,10);
image(life,80,10);
}
if (loose==2){
image(life,10,10);
image(life,45,10);
}
if (loose==1){
image(life,10,10);
}
// calling class action, movement
for (int i = 0; i<totalArrows; i++) {
theArrows[i].run();
if (theArrows[i].y>475 && theArrows[i].y<600) {
theArrows[i].inactive = true;
}
if(theArrows[i].did == false && theArrows[i].y>598) {
theArrows[i].lost = true;
}
if(theArrows[i].lost && theArrows[i].did == false && theArrows[i].wrongclick == false){
loose--;
theArrows[i].lost = false;
}
}
if (loose == 0){
textSize(32);
text("gameover",width/2,height/2);
for(int i=0; i<totalArrows;i++){
}
}
}
void keyPressed() {
if (key == 'p'){
// placing tha arrows. (i*105 = positioning) THIS PART IS AN ISSUE FOR SURE. SEE ARROW CLASS
for (int i= 0; i<totalArrows; i++) {
theArrows[i] = new arrowclass(-i*105);
}
loop();
}
}
void keyReleased() {
for (int i= 0; i<totalArrows; i++) {
if (theArrows[i].inactive && theArrows[i].did == false) {
if (keyCode == UP && theArrows[i].id == 3){
score++;
theArrows[i].did = true;
}
if (keyCode != UP && theArrows[i].id == 3){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == DOWN && theArrows[i].id == 0){
score++;
theArrows[i].did = true;
}
if (keyCode != DOWN && theArrows[i].id == 0){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == RIGHT && theArrows[i].id == 2){
score++;
theArrows[i].did = true;
}
if (keyCode != RIGHT && theArrows[i].id == 2){
loose--;
theArrows[i].wrongclick = true;
}
if (keyCode == LEFT && theArrows[i].id == 1){
score++;
theArrows[i].did = true;
}
if (keyCode != LEFT && theArrows[i].id == 1){
loose--;
theArrows[i].wrongclick = true;
}
}
}
}
And the arrow class:
class arrowclass{
int y;
int id;
boolean did;
boolean inactive;
boolean lost;
boolean wrongclick;
// proprieties of the class
arrowclass(int initY){
y = initY;
id = int(random(4));
did = false;
inactive = false;
lost = false;
wrongclick = false;
}
//actions
void run(){
image(imgList[id],width/2,y);
// score goes up, speed goes up
y += 2+score;
// reset arrow to default
if (y>600) {
y = -50;
id = int(random(4));
inactive = false;
did = false;
lost = false;
wrongclick = false;
}
}
}

using toString from other methods

I am trying to output the information from the Salaried class in the EmployeesApplet class using the toString method in Salaried, however i keep receiving the error
EmployeesApplet.java:292: error: non-static method toString() cannot be referenced from a static context
ta.append(Salaried.toString());
^
How do i get around this error to display the information correctly?
here is the Salaried class
public class Salaried extends Employee
{
private double weekly_salary;
public Salaried(String first_name, String last_name, int e, double w ) // one constructor
{
super(first_name,last_name, e);
weekly_salary = w;
}
public String toString()
{
return super.toString() + " \nWeekly Salary" + weekly_salary ;
} // toString method
}
and here is the EmployeesApplet class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
public void init()
{
this.setSize(420, 310);
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
private boolean fieldsExist(int i, int i2)
{
if(i == 0 && i2 == 3) // Checks Salaried worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty"); // Diplays error message in status area
tf[0].getTextField().requestFocus(); // Places focus in JTextField
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else if(tf[3].getText() == null || tf[3].getText().length() == 0)
{
showStatus("(a)Salried: Weekly Salary field is empty");
tf[3].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Hourly worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 4 && i2 == 5) // Checks Hourly worker the second time
{
if(tf[4].getText() == null || tf[4].getText().length() == 0)
{
showStatus("(b1) Hourly 1: Rate Per Hour field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else if(tf[5].getText() == null || tf[5].getText().length() == 0)
{
showStatus("(b2) Hourly 2: Hours Worked field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Commissioned worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 6 && i2 == 7) // Checks Commissioned second time
{
if(tf[6].getText() == null || tf[6].getText().length() == 0)
{
showStatus("(c1)Commissioned: Rate field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[7].getText() == null || tf[7].getText().length() == 0)
{
showStatus("(c2)Commissioned: Ratefield is empty");
tf[1].getTextField().requestFocus();
return false;
}
else
return true;
}
return false;
}
private boolean fieldsEmpty(int i, int i2, String[] a)
{
if(i == 4 && i2 == 7) // checks salaried
{
for (int index = 4; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus( a[index] + " should be empty"); // Diplays error message in status area
tf[index].getTextField().requestFocus(); // Places focus in JTextField
return true;
}
else return false;
} // end for
} // end if
if (i == 3 && i2 == 3) // checks hourly first time
{
if(tf[3].getText().length() != 0)
{
showStatus(a[3] + " field should be empty");
tf[3].getTextField().requestFocus();
return true;
}
} // end if
if(i == 6 && i2 == 7) // checks hourly second time
{
for (int index = 6; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
if(i == 3 && i2 == 5) // checks commissioned
{
for (int index = 3; index <= 5; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
return false;
}
public void actionPerformed(ActionEvent e)
{
showStatus("");
if (e.getSource() == cl) // Executes clear button is clicked
{
for (int i = 0; i < FIELDS; i++)
{
tf[i].getTextField().setText("");
tf[0].getTextField().requestFocus();
}
} // End clear if
if (e.getSource() != cl)
{
if(e.getSource() == sd) // checks for salaried employee
{
showStatus("Salaried");
fieldsExist(0,3);
fieldsEmpty(4,7, s);
ta.append(Salaried.toString());
} // end salaried
if(e.getSource() == hr) // checks for hourly employee
{
showStatus("Hourly");
fieldsExist(0,2);
fieldsExist(4,5);
fieldsEmpty(3,3, s);
fieldsEmpty(6,7, s);
} // end hourly
if(e.getSource() == cm) // checks for commissioned employee
{
showStatus("Commissioned");
fieldsExist(0,2);
fieldsExist(6,7);
fieldsEmpty(3,5, s);
} // end commisssioned
} // end if
} // End of actionPerformed
}
As the error states, toString() is not static, you need to run it on an instance of Salaried. e.g.
Salaried s = new Salaried();
s.toString(); // should work...
Without relevant section from EmployeeApplet I cannot advise further, note ta.append(Salaried.toString()); in the error message you posted, does not appear to correspond to fragment of EmployeeApplet you gave...

Java connect four victory check

I am a beginner at programming and I have been teaching myself as much as I can. I need help in a simpler way of checking for a victory instead of hard coding every possible combination.
I have no idea what to do.
here is my current code:
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class connectfour extends JFrame implements ActionListener
{
JLabel board[][] = new JLabel[8][7];
//JLabel board[] = new JLabel[64];
JButton action[] = new JButton[8];
JButton start;
JButton clear;
JFrame Frame = new JFrame();
ImageIcon red = new ImageIcon("red piece.jpeg");
ImageIcon black = new ImageIcon("blackpiece.jpeg");
boolean players = true;
//Integer[] numclick = new Integer[8];
int x;
int numclick1 = 7;
int numclick2 = 7;
int numclick3 = 7;
int numclick4 = 7;
int numclick5 = 7;
int numclick6 = 7;
int numclick7 = 7;
int numclick0 = 7;
public connectfour()
{
Frame.setSize(100,120);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setLayout(null);
Frame.setVisible(true);
start = new JButton("Start");
start.setBounds(0,0,100,100);
start.setVisible(true);
start.addActionListener(this);
Frame.add(start);
}
public void game()
{
for(int x = 0; x < 8 ; x++)
{
action[x] = new JButton();
action[x].setSize(100,40);
action[x].setLocation((x*100) + 50, 0);
action[x].addActionListener(this);
action[x].setVisible(true);
Frame.add(action[x]);
}
/**
board[1][1] = new JLabel();
board[1][1].setBounds(50,40,100,100);
board[1][1].setVisible(true);
board[1][1].setOpaque(true);
board[1][1].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[1][1]);
**/
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new JLabel();
board[i][j].setSize(100,100);
board[i][j].setLocation((i*100)+50,(j*100)+40);
board[i][j].setOpaque(true);
board[i][j].setVisible(true);
board[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[i][j]);
}
}
clear = new JButton("Clear");
clear.setBounds(850,100,100,50);
clear.addActionListener(this);
clear.setVisible(true);
Frame.add(clear);
}
public void boardsize()
{
Frame.setSize(950,800);
}
public static void main(String args[])
{
new connectfour();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
boardsize();
start.setVisible(false);
game();
}
for(x = 0;x < 8 ;x ++)
{
if(e.getSource() == action[x])
{
//numclick[x]++;
if(x == 0)
{
numclick0--;
if(players == true)
{
board[x][numclick0].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick0].setIcon(black);
players = true;
break;
}
}
if(x == 1)
{
numclick1--;
if(players == true)
{
board[x][numclick1].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick1].setIcon(black);
players = true;
break;
}
}
if(x == 2)
{
numclick2--;
if(players == true)
{
board[x][numclick2].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick2].setIcon(black);
players = true;
break;
}
}
if(x == 3)
{
numclick3--;
if(players == true)
{
board[x][numclick3].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick3].setIcon(black);
players = true;
break;
}
}
if(x == 4)
{
numclick4--;
if(players == true)
{
board[x][numclick4].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick4].setIcon(black);
players = true;
break;
}
}
if(x == 5)
{
numclick5--;
if(players == true)
{
board[x][numclick5].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick5].setIcon(black);
players = true;
break;
}
}
if(x == 6)
{
numclick6--;
if(players == true)
{
board[x][numclick6].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick6].setIcon(black);
players = true;
break;
}
}
if(x == 7)
{
numclick7--;
if(players == true)
{
board[x][numclick7].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick7].setIcon(black);
players = true;
break;
}
}
System.out.println(x);
System.out.println();
}
}
if(e.getSource() == clear)
{
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 7; y++)
{
board[x][y].setIcon(null);
numclick1 = 7;
numclick2 = 7;
numclick3 = 7;
numclick4 = 7;
numclick5 = 7;
numclick6 = 7;
numclick7 = 7;
numclick0 = 7;
players = true;
for(int j = 0; j < 8 ; j++)
{
action[j].setEnabled(true);
}
}
}
}
if(numclick0 == 0)
{
action[0].setEnabled(false);
}
if(numclick1 == 0)
{
action[1].setEnabled(false);
}
if(numclick2 == 0)
{
action[2].setEnabled(false);
}
if(numclick3 == 0)
{
action[3].setEnabled(false);
}
if(numclick4 == 0)
{
action[4].setEnabled(false);
}
if(numclick5 == 0)
{
action[5].setEnabled(false);
}
if(numclick6 == 0)
{
action[6].setEnabled(false);
}
if(numclick7 == 0)
{
action[7].setEnabled(false);
}
}
public void winner()
{
}
}
I would use a recursive method that checks the horizontal, vertical, and both diagonals.
As i was reading your code I realized you don't keep track(may have missed it) of where players are.. I recommend and array for this called grid[][] Mapping an array to your JLabels will go a long way.
Ill give an example of negative vertical check..
public Boolean checkVertical(Boolean player, int x, int y){
if(solveHelper(player, x, y, -1, 0) => 4) return true;
return false;
}
public int solveHelper(Boolean player, int x, int y, int addX, int addY){
if(x == 0 || x == size || y == 0 || y == size || grid[x][y].player != player)
return 0;
return solverHelper(player, x+addX, y+addY, addX, addY) + 1);
}
Now how can you create and use these methods for yourself?
you need to create a new methods for each of the horizontal, vertical, and both diagonals to check for all of them you call solveHelper with different properties in addX and addY that correspond with the direction you want to go. For instance, if you want to check the horizontal you need do make addY == 1 and addY == -1 with both values for addX == 0 by doing a solveHelper + solverHelper with these two values changed.
Other notes...
Some things you need to need to keep in mind is that how connect four actually runs. When you click on a row a piece falls down to the smallest unoccupied element in that particular column. Just something you should keep in mind when writing your game logic.
Cheers.

java, "enter program argument" error?

I'm fairly new to the java programming. Below i have my program and the error that keeps appearing. I do not know what it means, if someone could please help me. i am using crimson editor, my program compiles fine just when a window asking me "enter program arguments" that this error appears.If someone could please explain to me what it means. Thank you.
// my program
package test.rim.bbapps.testcase.lib;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class michaeltictactoe2 implements ActionListener {
/* Instance variables */
private JFrame window = new JFrame (" TicTacToe");
private JButton button1 = new JButton ("") ;
private JButton button2 = new JButton ("") ;
private JButton button3 = new JButton ("") ;
private JButton button4 = new JButton ("") ;
private JButton button5 = new JButton ("") ;
private JButton button6 = new JButton ("") ;
private JButton button7 = new JButton ("") ;
private JButton button8 = new JButton ("") ;
private JButton button9 = new JButton ("") ;
private String letter = "";
private int count = 0;
private boolean win = false;
public michaeltictactoe2 () {
//* Create Window * /
window.setSize (300,300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout ( new GridLayout (3, 3));
/* Adding buttons to the window*/
window.add(button1);
window.add(button2);
window.add(button3);
window.add(button4);
window.add(button5);
window.add(button6);
window.add(button7);
window.add(button8);
window.add(button9);
/* Add the action listener to the Button */
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
//* make the window visible * /
window.setVisible (true) ;
}
public void actionPerformed (ActionEvent a) {
count++;
/* Calculate who's turn it is */
if (count == 1 || count == 3|| count == 5 || count == 7 || count == 9) {
letter = "X";
} else if ( count == 2 || count == 4 || count == 6 || count == 8 ) {
letter = "O";
}
/* Display X's or O's on the buttons */
if ( a.getSource () == button1) {
button1.setText ( letter ) ;
button1.setEnabled (false);
} else if (a.getSource () == button2) {
button2.setText(letter);
button2.setEnabled(false);
} else if (a.getSource () == button3) {
button3.setText(letter);
button3.setEnabled(false);
} else if (a.getSource () == button4) {
button4.setText(letter);
button4.setEnabled(false);
} else if (a.getSource () == button5) {
button5.setText(letter);
button5.setEnabled(false);
} else if (a.getSource () == button6) {
button6.setText(letter);
button6.setEnabled(false);
} else if (a.getSource () == button7) {
button7.setText(letter);
button7.setEnabled(false);
} else if (a.getSource () == button8) {
button8.setText(letter);
button8.setEnabled(false);
} else if (a.getSource () == button9) {
button9.setText(letter);
button9.setEnabled(false);
}
// * Determine who won */
// horizontal wins
if ( button1.getText () == button2.getText ()
&& button2.getText () == button3.getText ()
&& button1.getText () != "") {
win = true;
} else if ( button4.getText () == button5.getText ()
&& button5.getText () == button6.getText ()
&& button4.getText () != "") {
win = true;
} else if ( button7.getText () == button8.getText ()
&& button8.getText () == button9.getText ()
&& button7.getText () != "") {
win = true;
// Verticle wins
} else if (button1.getText() == button4.getText ()
&& button4.getText() == button7.getText ()
&& button1.getText() != "") {
win = true;
} else if (button2.getText() == button5.getText()
&& button5.getText() == button8.getText()
&& button2.getText() != "") {
win = true;
} else if ( button3.getText() == button6.getText()
&& button6.getText() == button9.getText()
&& button9.getText() != "") {
win = true ;
// Diagonal wins
} else if (button1.getText() == button5.getText()
&& button5.getText() == button9.getText()
&& button1.getText() != "") {
win = true;
} else if (button3.getText() == button5.getText()
&& button5.getText() == button7.getText()
&& button3.getText() != "") {
win = true;
} else {
win = false ;
}
/* show a dialog is someone wins or the game is tie*/
if ( win == true) {
JOptionPane.showMessageDialog(null, letter + " YOU WIN!");
} else if (count == 9 && win == false) {
JOptionPane.showMessageDialog ( null , " Tie Game!" ) ;
}
}
public static void main (String [] args) {
new michaeltictactoe2 () ;
}
}
error:
---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.6.0_22\bin\java.exe" michaeltictactoe1
java.lang.NoClassDefFoundError: michaeltictactoe1 (wrong name: test/rim/bbapps/testcase/lib/michaeltictactoe1)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: michaeltictactoe1. Program will exit.
Exception in thread "main"
> Terminated with exit code 1.
thanks again.
You are compiling michaeltictactoe1 and the class name is michaeltictactoe2
compile with
javac michaeltictactoe2.java
then run with
java michaeltictactoe2
read http://www.oracle.com/technetwork/java/compile-136656.html
Looks like the class name does not match the file name (michaeltictactoe1 vs. michaeltictactoe2)

Categories