Why doesn't boolean value switch? - java

First I want to say thanks for any assistance. I'm relatively new to Java programming. I built a simple TicTacToe game, and I'm having a little trouble.
Every once in a while "X" or "O" will be played twice in a row. I have a boolean variable that is supposed to switch from true to false to change "X" to "O" as each player takes a turn, but for some reason it isn't switching at random times.
I'm thinking it may be a problem with Eclipse or something, because I don't understand why else it would do this.
Below is the code for the game:
public class gameMain {
Boolean player = true;
JPanel gameBoard;
JButton[] b = new JButton[10];
Font font = new Font("Arial", Font.BOLD, 99);
ListenForButtons lfb = new ListenForButtons();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new gameMain();
}
});
}
public gameMain() {
JFrame j = new JFrame("TicTacToe");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setLocationRelativeTo(null);
j.setSize(400, 400);
gameBoard = new JPanel();
gameBoard.setLayout(new GridLayout(3, 3));
b[1] = new JButton("");
b[1].addActionListener(lfb);
b[1].setContentAreaFilled(false);
b[1].setFont(font);
b[1].setBorder(BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK));
b[2] = new JButton("");
b[2].addActionListener(lfb);
b[2].setContentAreaFilled(false);
b[2].setFont(font);
b[2].setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK));
b[3] = new JButton("");
b[3].addActionListener(lfb);
b[3].setContentAreaFilled(false);
b[3].setFont(font);
b[3].setBorder(BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK));
b[4] = new JButton("");
b[4].addActionListener(lfb);
b[4].setContentAreaFilled(false);
b[4].setFont(font);
b[4].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK));
b[5] = new JButton("");
b[5].addActionListener(lfb);
b[5].setContentAreaFilled(false);
b[5].setFont(font);
b[5].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, Color.BLACK));
b[6] = new JButton("");
b[6].addActionListener(lfb);
b[6].setContentAreaFilled(false);
b[6].setFont(font);
b[6].setBorder(BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK));
b[7] = new JButton("");
b[7].addActionListener(lfb);
b[7].setContentAreaFilled(false);
b[7].setFont(font);
b[7].setBorder(BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK));
b[8] = new JButton("");
b[8].addActionListener(lfb);
b[8].setContentAreaFilled(false);
b[8].setFont(font);
b[8].setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
b[9] = new JButton("");
b[9].addActionListener(lfb);
b[9].setContentAreaFilled(false);
b[9].setFont(font);
b[9].setBorder(BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK));
gameBoard.add(b[1]);
gameBoard.add(b[2]);
gameBoard.add(b[3]);
gameBoard.add(b[4]);
gameBoard.add(b[5]);
gameBoard.add(b[6]);
gameBoard.add(b[7]);
gameBoard.add(b[8]);
gameBoard.add(b[9]);
j.add(gameBoard);
j.setVisible(true);
}
public class ListenForButtons implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b[1]) {
setSquare(b[1]);
}
if (e.getSource() == b[2]) {
setSquare(b[2]);
}
if (e.getSource() == b[3]) {
setSquare(b[3]);
}
if (e.getSource() == b[4]) {
setSquare(b[4]);
}
if (e.getSource() == b[5]) {
setSquare(b[5]);
}
if (e.getSource() == b[6]) {
setSquare(b[6]);
}
if (e.getSource() == b[7]) {
setSquare(b[7]);
}
if (e.getSource() == b[8]) {
setSquare(b[8]);
}
if (e.getSource() == b[9]) {
setSquare(b[9]);
}
checkForWin();
}
}
public void setSquare(JButton button) {
if (player) {
button.setText("X");
player = false;
button.removeActionListener(lfb);
} else {
button.setText("O");
player = true;
button.removeActionListener(lfb);
}
}
public void checkForWin() {
if ((b[1].getText().equals("X") && b[2].getText().equals("X") && b[3].getText().equals("X"))
|| (b[4].getText().equals("X") && b[5].getText().equals("X") && b[6].getText().equals("X"))
|| (b[7].getText().equals("X") && b[8].getText().equals("X") && b[9].getText().equals("X"))
|| (b[1].getText().equals("X") && b[4].getText().equals("X") && b[7].getText().equals("X"))
|| (b[2].getText().equals("X") && b[5].getText().equals("X") && b[8].getText().equals("X"))
|| (b[3].getText().equals("X") && b[6].getText().equals("X") && b[9].getText().equals("X"))
|| (b[1].getText().equals("X") && b[5].getText().equals("X") && b[9].getText().equals("X"))
|| (b[3].getText().equals("X") && b[5].getText().equals("X") && b[7].getText().equals("X"))) {
JOptionPane.showMessageDialog(null, "X WINS THE GAME!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
} else if ((b[1].getText().equals("O") && b[2].getText().equals("O") && b[3].getText().equals("O"))
|| (b[4].getText().equals("O") && b[5].getText().equals("O") && b[6].getText().equals("O"))
|| (b[7].getText().equals("O") && b[8].getText().equals("O") && b[9].getText().equals("O"))
|| (b[1].getText().equals("O") && b[4].getText().equals("O") && b[7].getText().equals("O"))
|| (b[2].getText().equals("O") && b[5].getText().equals("O") && b[8].getText().equals("O"))
|| (b[3].getText().equals("O") && b[6].getText().equals("O") && b[9].getText().equals("O"))
|| (b[1].getText().equals("O") && b[5].getText().equals("O") && b[9].getText().equals("O"))
|| (b[3].getText().equals("O") && b[5].getText().equals("O") && b[7].getText().equals("O"))) {
JOptionPane.showMessageDialog(null, "O WINS THE GAME!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
} else if (!b[1].getText().equals("") && !b[2].getText().equals("") && !b[3].getText().equals("")
&& !b[4].getText().equals("") && !b[5].getText().equals("") && !b[6].getText().equals("")
&& !b[7].getText().equals("") && !b[8].getText().equals("") && !b[9].getText().equals("")) {
JOptionPane.showMessageDialog(null, "Cats Game!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
}
}
public void resetBoard() {
for (int i = 1; i <= b.length - 1; i++) {
b[i].setText("");
}
for (int i = 1; i <= b.length - 1; i++) {
b[i].addActionListener(lfb);
}
player = true;
}
}

When ResetBoard() is called and not every button was pressed, then you end up having multiple ActionListeners assigned to those not used buttons.
Here is a example resetBoard() method:
public void resetBoard() {
// Fixed the loop index. Was: (int i = 1; i <= b.length - 1; i++)
for (int i = 0; i < b.length; i++) {
b[i].setText("");
// Adding a listener only if there isn't one already
if (b[i].getActionListeners().length < 1)
b[i].addActionListener(lfb);
}
player = true;
}
As #MadProgrammer suggested i refactored also the setSquare() method:
public void setSquare(JButton button) {
if (player) {
button.setText("X");
} else {
button.setText("O");
}
button.removeActionListener(lfb);
player = !player;
}

Related

How to switch between 2 colors in Java Jbuttons after every click

I have been making a color-based Tic Tac Toe game using Java Swing and Java AWT and have more or less finished the project, however there is still one problem that needs to be fixed in order to be a proper Tic Tac Toe game. The colors that are supposed to be used is Orange (X) and blue (O), however for some reason even when checking each turn iteration it refuses to switch colors after every click and at this point I am lost. Any help is appreciated
Board.java:
public class Board extends JPanel {
boolean gameRunning = true;
private final JButton[][] grid = new JButton[3][3];
JFrame board;
JPanel panel;
public Board() {
initBoard();
}
private void makePanel() {
panel = new JPanel();
panel.setBackground(Color.lightGray);
panel.setLayout(new GridLayout(3, 3));
setBoard();
board.add(panel);
}
private void initBoard() {
int BOARD_WIDTH = 800;
int BOARD_HEIGHT = 600;
board = new JFrame();
board.setTitle("JTicTacToe");
board.setSize(BOARD_WIDTH, BOARD_HEIGHT);
board.setResizable(false);
board.setLocationRelativeTo(null);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
makePanel();
board.setVisible(true);
}
private void setBoard() {
//Loop through 2D array
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = new JButton();
grid[row][col].setOpaque(true);
grid[row][col].setBorderPainted(false);
grid[row][col].addActionListener(new ButtonListener());
panel.add(grid[row][col]);
}
}
validate();
}
protected class ButtonListener implements ActionListener {
Color defaultColor = new Color(238,238,238);
protected void check(int moves) {
//Rows
for (int c = 0; c < 3; c++) {
if (!defaultColor.equals(grid[c][0].getBackground()) && grid[c][0].getBackground() == grid[c][1].getBackground() && grid[c][0].getBackground() == grid[c][2].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
}
//Verticals
for (int c = 0; c < 3; c++) {
if (!defaultColor.equals(grid[0][c].getBackground()) && grid[0][c].getBackground() == grid[1][c].getBackground() && grid[0][c].getBackground() == grid[2][c].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
}
//Check diagonals
if (!defaultColor.equals(grid[0][0].getBackground()) && grid[0][0].getBackground() == grid[1][1].getBackground() && grid[0][0].getBackground() == grid[2][2].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");}
if (!defaultColor.equals(grid[0][2].getBackground()) && grid[0][2].getBackground() == grid[1][1].getBackground() && grid[0][2].getBackground() == grid[2][0].getBackground()) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Game Over!");
}
//Check draw if game goes to 9 moves
if(moves == 9) {
gameRunning = false;
JOptionPane.showMessageDialog(null, "Draw!");
}
}
#Override
public void actionPerformed(ActionEvent e) {
int turns = 0;
if (e.getSource() == grid[0][0]) {
turns++;
if (turns % 2 == 0) {
grid[0][0].setBackground(Color.orange);
check(turns);
} else {
grid[0][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[0][1]) {
turns++;
if (turns % 2 == 0) {
grid[0][1].setBackground(Color.orange);
check(turns);
} else {
grid[0][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[0][2]) {
turns++;
if (turns % 2 == 0) {
grid[0][2].setBackground(Color.orange);
check(turns);
} else {
grid[0][2].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][0]) {
turns++;
if (turns % 2 == 0) {
grid[1][0].setBackground(Color.orange);
check(turns);
} else {
grid[1][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][1]) {
turns++;
if (turns % 2 == 0) {
grid[1][1].setBackground(Color.orange);
check(turns);
} else {
grid[1][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[1][2]) {
turns++;
if (turns % 2 == 0) {
grid[1][2].setBackground(Color.orange);
check(turns);
} else {
grid[1][2].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][0]) {
turns++;
if (turns % 2 == 0) {
grid[2][0].setBackground(Color.orange);
check(turns);
} else {
grid[2][0].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][1]) {
turns++;
if (turns % 2 == 0) {
grid[2][1].setBackground(Color.orange);
check(turns);
} else {
grid[2][1].setBackground(Color.blue);
check(turns);
}
} else if (e.getSource() == grid[2][2]) {
turns++;
if (turns % 2 == 0) {
grid[2][2].setBackground(Color.orange);
check(turns);
} else {
grid[2][2].setBackground(Color.blue);
check(turns);
}
} else {
JOptionPane.showMessageDialog(null, "Invalid");
}
System.out.println(turns);
}
}
}
If you want to make the code prettier:
The variable gameRunning is set but it is never used. You can remove it and the program will still behave the same. Or you can start using it. But just giving it values without using those values is unnecessary work.
The variables at the top should be private (grid is private, but eg board is not)
You can use a loop to shorten the actionPerformed method (note that I added a return;):
#Override
public void actionPerformed(ActionEvent e) {
for (int col = 0; col < 3; col++) {
for (int row = 0; row < 3; row++) {
if (e.getSource() == grid[col][row]) {
turns++;
if (turns % 2 == 0) {
grid[col][row].setBackground(Color.orange);
check(turns);
} else {
grid[col][row].setBackground(Color.blue);
check(turns);
}
System.out.println(turns);
return;
}
}
}
JOptionPane.showMessageDialog(null, "Invalid");
}
You set the variable turns to 0 every time a button is clicked (ie every time actionPerformed is called). You need to make turns global (same as eg grid).

JavaFX Program lags

So I'm a college student presently learning Java and JavaFX by myself, with some help from you all.
I'm trying to start by making a relatively simple calculator, customizing it with some CSS. My program works fine, the only real problem is the lag whenever I actually calculate what I want. So I'll go, "5 + 5 =" and as soon as I hit equals it lags and then shows "10". Not sure why and I haven't found much on it.
Thanks for the help in advance.
NOTE: If you have any other suggestions to help me improve my code, feel free to post it. I have a long way to go.
import javafx.application.Application;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javax.script.ScriptEngineManager;
import java.math.BigDecimal;
import javax.script.ScriptEngine;
public class practice3 extends Application {
Stage window;
Button plus,
minus,
divide,
multiply,
clear,
zero,
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
decimal,
equals;
TextField display;
double total,
num1;
String input = "";
String equationInput = ""; //equationInput will store all data up to a symbol is pressed
Label equation;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Simple Calculator");
//Display Text Field
display = new TextField();
display.setEditable(false);
display.setPrefHeight(70);
display.setFont(Font.font("Verdana", 50));
equation = new Label();
equation.setPrefHeight(70);
equation.setFont(Font.font("Verdana", 12));
equation.setText(equationInput);
equation.setPrefWidth(209);
equation.setPadding(new Insets(0, 0, 3, 3));
//Buttons
plus = new Button("+");
plus.setPrefSize(70, 70);
plus.setOnAction(e - >operationButton("+"));
minus = new Button("-");
minus.setPrefSize(70, 70);
minus.setOnAction(e - >operationButton("-"));
divide = new Button("/");
divide.setPrefSize(70, 70);
divide.setOnAction(e->operationButton("/"));
multiply = new Button("*");
multiply.setPrefSize(70, 70);
multiply.setOnAction(e->operationButton("*"));
clear = new Button("C");
clear.setPrefSize(70, 70);
clear.setOnAction(e->clearButton());
equals = new Button("=");
equals.setPrefSize(70, 70);
equals.setOnAction(e->{
try {
calculate();
} catch(Exception e1) {
System.out.println("Error in code.");
}
});
decimal = new Button(".");
decimal.setPrefSize(70, 70);
decimal.setOnAction(e->decimalButton());
//Numbers
one = new Button("1");
one.setPrefSize(70, 70);
one.setOnAction(e->numberButton("1"));
two = new Button("2");
two.setPrefSize(70, 70);
two.setOnAction(e->numberButton("2"));
three = new Button("3");
three.setPrefSize(70, 70);
three.setOnAction(e->numberButton("3"));
four = new Button("4");
four.setPrefSize(70, 70);
four.setOnAction(e->numberButton("4"));
five = new Button("5");
five.setPrefSize(70, 70);
five.setOnAction(e->numberButton("5"));
six = new Button("6");
six.setPrefSize(70, 70);
six.setOnAction(e->numberButton("6"));
seven = new Button("7");
seven.setPrefSize(70, 70); //WidthxHeight
seven.setOnAction(e->numberButton("7"));
eight = new Button("8");
eight.setPrefSize(70, 70);
eight.setOnAction(e->numberButton("8"));
nine = new Button("9");
nine.setPrefSize(70, 70);
nine.setOnAction(e->numberButton("9"));
zero = new Button("0");
zero.setPrefSize(70, 70);
zero.setOnAction(e->numberButton("0"));
BorderPane layout = new BorderPane();
GridPane grid = new GridPane();
layout.setCenter(grid);
layout.setTop(display);
//Setting Constraints for Buttons and Equation Display
grid.setConstraints(seven, 0, 1);
grid.setConstraints(eight, 1, 1);
grid.setConstraints(nine, 2, 1);
grid.setConstraints(clear, 3, 0);
grid.setConstraints(four, 0, 2);
grid.setConstraints(five, 1, 2);
grid.setConstraints(six, 2, 2);
grid.setConstraints(plus, 3, 1);
grid.setConstraints(one, 0, 3);
grid.setConstraints(two, 1, 3);
grid.setConstraints(three, 2, 3);
grid.setConstraints(minus, 3, 2);
grid.setConstraints(decimal, 0, 4);
grid.setConstraints(zero, 1, 4);
grid.setConstraints(multiply, 3, 3);
grid.setConstraints(divide, 3, 4);
grid.setConstraints(equals, 2, 4);
grid.setConstraints(equation, 0, 0, 3, 1);
display.setStyle("-fx-focus-color: transparent;");
grid.getChildren().addAll(seven, eight, nine, clear, four, five, six, plus, one, two, three, minus, decimal, zero, multiply, divide, equals, equation);
layout.setPadding(new Insets(5, 5, 5, 5));
display.setText("0");
Scene scene = new Scene(layout, 290, 462);
//Keyboard Events
scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> {
if (key.getCode() == KeyCode.DIGIT1 || key.getCode() == KeyCode.NUMPAD1) {
numberButton("1");
}
else if (key.getCode() == KeyCode.DIGIT2 || key.getCode() == KeyCode.NUMPAD2) {
numberButton("2");
}
else if (key.getCode() == KeyCode.DIGIT3 || key.getCode() == KeyCode.NUMPAD3) {
numberButton("3");
}
else if (key.getCode() == KeyCode.DIGIT4 || key.getCode() == KeyCode.NUMPAD4) {
numberButton("4");
}
else if (key.getCode() == KeyCode.DIGIT5 || key.getCode() == KeyCode.NUMPAD5) {
numberButton("5");
}
else if (key.getCode() == KeyCode.DIGIT6 || key.getCode() == KeyCode.NUMPAD6) {
numberButton("6");
}
else if (key.getCode() == KeyCode.DIGIT7 || key.getCode() == KeyCode.NUMPAD7) {
numberButton("7");
}
else if (key.getCode() == KeyCode.DIGIT8 || key.getCode() == KeyCode.NUMPAD8) {
numberButton("8");
}
else if (key.getCode() == KeyCode.DIGIT9 || key.getCode() == KeyCode.NUMPAD9) {
numberButton("9");
}
else if (key.getCode() == KeyCode.DIGIT0 || key.getCode() == KeyCode.NUMPAD0) {
numberButton("0");
}
else if (key.getCode() == KeyCode.PERIOD || key.getCode() == KeyCode.DECIMAL) {
decimalButton();
}
else if (key.getCode() == KeyCode.ADD) {
operationButton("+");
}
else if (key.getCode() == KeyCode.SUBTRACT) {
operationButton("-");
}
else if (key.getCode() == KeyCode.MULTIPLY) {
operationButton("*");
}
else if (key.getCode() == KeyCode.DIVIDE) {
operationButton("/");
}
else if (key.getCode() == KeyCode.EQUALS) {
try {
calculate();
} catch(Exception e1) {
System.out.println("Error in code.");
}
}
else if (key.getCode() == KeyCode.C) {
clearButton();
}
});
scene.getStylesheets().add("practice3.css");
equation.getStyleClass().add("equation-label");
//End
window.setScene(scene);
window.show();
}
private void clearButton() {
input = "";
total = 0;
num1 = 0;
equationInput = "";
display.setText("0");
equation.setText("");
}
private void numberButton(String value) {
input += value;
display.setText(input);
}
private void decimalButton() {
int check;
if (input.indexOf(".") == -1) {
if (input == "") {
input += "0.";
display.setText(input);
}
else {
input += ".";
display.setText(input);
}
}
}
private void operationButton(String symbol) {
equationInput += input;
input = "";
if (symbol == "+") {
equationInput += " + ";
}
else if (symbol == "-") {
equationInput += " - ";
}
else if (symbol == "*") {
equationInput += " * ";
}
else if (symbol == "/") {
equationInput += " / ";
}
equation.setText(equationInput);
display.setText("0");
}
private void calculate() throws Exception {
String answer = "0";
double answer1;
Object eval;
equationInput += input;
input = "";
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
eval = engine.eval(equationInput);
answer1 = new BigDecimal(eval.toString()).doubleValue();
answer = String.valueOf(answer1);
equationInput += " = ";
display.setText(answer);
equation.setText(equationInput);
}
}
Also, I would like to mention that I'm not very good at organization yet so if anything seems confusing feel free to ask!

java timer will not work

I'm trying to set an int, defined in the class, to 0, 5 seconds after it has been changed to more than 0. Any help would be greatly appreciated!
I have a program where users have to input an addition to a score.
private void inputResponse(int pNum) {
Patient p = null;
p = patientList.get(pNum);
Map<String, List<Double>> pData = sEWSTracker.get(p);
List<Double> sEp = pData.get("SEW");
Double sEWS = sEp.get(sEp.size() - 1);
Component frame = null;
Object[] response = {"Alert", "Verbal", "Pain", "Unresponsive"};
String r = (String) JOptionPane.showInputDialog(
frame,
"Please input the patient’s response external stimulus:\n", "Please Report Patient's Response Level",
JOptionPane.PLAIN_MESSAGE, null,
response, response[0]);
int reACT = 0;
if (r.equals("Verbal")) {
if (pNum == 0) {
p0checked = 1;
}
if (pNum == 1) {
p1checked = 1;
}
if (pNum == 2) {
p2checked = 1;
}
if (pNum == 3) {
p3checked = 1;
}
if (pNum == 4) {
p4checked = 1;
}
if (pNum == 4) {
p5checked = 1;
}
}
if (r.equals("Pain")) {
if (pNum == 0) {
p0checked = 2;
}
if (pNum == 1) {
p1checked = 2;
}
if (pNum == 2) {
p2checked = 2;
}
if (pNum == 3) {
p3checked = 2;
}
if (pNum == 4) {
p4checked = 2;
}
if (pNum == 4) {
p5checked = 2;
}
}
if (r.equals("Unresponsive")) {
if (pNum == 0) {
p0checked = 3;
}
if (pNum == 1) {
p1checked = 3;
}
if (pNum == 2) {
p2checked = 3;
}
if (pNum == 3) {
p3checked = 3;
}
if (pNum == 4) {
p4checked = 3;
}
if (pNum == 4) {
p5checked = 3;
}
}
Double sEWP = (reACT * 1.0) + sEWS;
List<Double> soEWS = pData.get("SEW");
soEWS.add(sEWP);
this.repaint();
sEWSreact(pNum);
}
Until they do the representation has a little message on it saying "Partial Score":
(for example)
if (p0checked == 0) {
g2.setColor(darkOrange);
g2.fillRoundRect(250, 152, 120, 35, 10, 10);
g2.setColor(mellowOrange);
g2.fillRoundRect(252, 154, 116, 31, 10, 10);
g2.setColor(darkBlue);
g2.setFont(helvetica1);
g2.drawString("Partial", 272, 170);
g2.setFont(verdanda4);
g2.setColor(Color.white);
g2.drawString("Click here to update", 258, 182);
}
}
And then a timer that resets the additional score to 0, in order to make the partial score notice come back and the score go back down to the original. ...however, nothing happens
if (p0checked > 0) {
Timer tim = new Timer(5 * 1000, new ActionListener() {#Override
public void actionPerformed(ActionEvent e) {
if (timSec >= 1) {
p0checked = 0;
}
timSec++;
}
});
tim.start();
}
timSec is defined (as 0) in the class also.

Adding a main to a pre existing program

I wrote a fairly simple program using a GUI template to learn about adding some form of GUI in java. I completed the program only to discover that it cant be run outside of the IDE without a main method. The program works fine inside Eclipse IDE, but useless otherwise. How do I go about adding a main class so it can be executed as a .jar?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
}
If you insist on keeping it as an Applet, make another class and do this:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
Game g = new Game();
g.init();
frame.getContentPane().add(g);
frame.pack();
frame.setVisible(true);
}
}
You can convert JApplet to JFrame - Change your public init() method to public static void main (String args[]).Then create an instance of JFrame
JFrame frame = new JFrame(); Then add components to it.
or
Add existing applet to JFrame - Adding JApplet into JFrame
So using second method your code would be -
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JApplet implements ActionListener {
// Create all labels, textfields and buttons needed (in order)
/**
* This is a tic tac toe game made with the purposes of learning java
*/
private static final long serialVersionUID = 1L;
JButton firstButton;
JButton secondButton;
JButton thirdButton;
JButton fourthButton;
JButton fithButton;
JButton sixthButton;
JButton seventhButton;
JButton eighthButton;
JButton ninthButton;
//this is the position value checker which are later set to x and o
String[] posCheck = { "", "", "", "", "", "", "", "", "" };
// score count JLABELs to display the score inside the game pane.
JLabel scoreP1;
JLabel scoreP2;
// this is used for formatting purposes or something like that, I guess.
JLabel blank;
// score count variables for both players, they both start at 0.
int scoreCount1 = 0, scoreCount2 = 0;
int gamesPlayed = -1;
boolean gameDone = false;
int k;
String prevWinner = "";
// Create any global variables/arrays needed later in the program (final)
Container pane = getContentPane();
//this sets the tile to X or O depending on who's turn it is
String[] symbol = { "O", "X" };
int turnCounter = 0;
int tieChecker = 0;
// Sets up GUI components.
public void init() {
pane.setLayout(new GridLayout(4, 3));
setSize(500, 500);
// Adds jlabel for scores
scoreP1 = new JLabel();
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
scoreP2 = new JLabel();
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank = new JLabel();
blank.setText(prevWinner);
// these are the JButtons that go in the game panel along with action
// listeners
firstButton = new JButton();
firstButton.addActionListener(this);
secondButton = new JButton();
secondButton.addActionListener(this);
thirdButton = new JButton();
thirdButton.addActionListener(this);
fourthButton = new JButton();
fourthButton.addActionListener(this);
fithButton = new JButton();
fithButton.addActionListener(this);
sixthButton = new JButton();
sixthButton.addActionListener(this);
seventhButton = new JButton();
seventhButton.addActionListener(this);
eighthButton = new JButton();
eighthButton.addActionListener(this);
ninthButton = new JButton();
ninthButton.addActionListener(this);
pane.add(firstButton, 0); // second parameter is the index on pane
pane.add(secondButton, 1);
pane.add(thirdButton, 2);
pane.add(fourthButton, 3);
pane.add(fithButton, 4);
pane.add(sixthButton, 5);
pane.add(seventhButton, 6);
pane.add(eighthButton, 7);
pane.add(ninthButton, 8);
pane.add(scoreP1);
pane.add(blank);
pane.add(scoreP2);
gamesPlayed++;
setContentPane(pane);
} // init method
// checks for mouse clicks here.
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if (e.getSource() == firstButton)
revealButton(firstButton, 0);
else if (e.getSource() == secondButton)
revealButton(secondButton, 1);
else if (e.getSource() == thirdButton)
revealButton(thirdButton, 2);
else if (e.getSource() == fourthButton)
revealButton(fourthButton, 3);
else if (e.getSource() == fithButton)
revealButton(fithButton, 4);
else if (e.getSource() == sixthButton)
revealButton(sixthButton, 5);
else if (e.getSource() == seventhButton)
revealButton(seventhButton, 6);
else if (e.getSource() == eighthButton)
revealButton(eighthButton, 7);
else if (e.getSource() == ninthButton)
revealButton(ninthButton, 8);
}
} // actionPerformed method
// respond to button pushed
public void revealButton(JButton button, int index) {
// removes the indicated button from pane
pane.remove(button);
// creates a new text field to take the place of the button, makes it
// uneditable and sets background colour
JTextField textField = new JTextField();
textField.setEditable(false);
textField.setBackground(Color.WHITE);
// sets the alignment for the text in the field
textField.setHorizontalAlignment(SwingConstants.CENTER);
// adds the new textfield to the pane at the location of the old button
pane.add(textField, index);
posCheck[index] = symbol[(turnCounter % 2)];
prevWinner = "Player (" + symbol[(turnCounter % 2)]
+ ") is the winner!";
// re-creates pane with new information
setContentPane(pane);
// this sets the text field to either X or O depending who placed last.
textField.setText(symbol[(turnCounter) % 2]);
button.setEnabled(false);
// this is a counter to check if it is a cats game.
tieChecker++;
// check for winner X here
if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
|| ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
|| ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
|| ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
|| ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
|| ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
|| ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount1++;
scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
blank.setText("Player (X) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if O has won the game.
else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
|| ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
|| ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
|| ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
|| ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
|| ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
|| ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
// this part updates the winner score then refreshes the text field
// to reflect the change
scoreCount2++;
scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
blank.setText("Player (O) Is the winner.");
gameDone = true;
turnCounter++;
}
// this checks if there has been a tie in the game
else if (tieChecker >= 9) {
prevWinner = ("It's a cat's game!");
tieChecker = 0;
gameDone = true;
turnCounter++;
}
// this makes sure the game doesnt end prematurely
else {
gameDone = false;
}
// this if statement is engaged when the game is done and resets the
// board
if (gameDone == true) {
pane.removeAll();
textField.removeAll();
tieChecker = 0;
init();
posCheck[0] = "";
posCheck[1] = "";
posCheck[2] = "";
posCheck[3] = "";
posCheck[4] = "";
posCheck[5] = "";
posCheck[6] = "";
posCheck[7] = "";
posCheck[8] = "";
posCheck[9] = "";
}// end of reset sequence
turnCounter++;
blank.setText("Games Played: " + gamesPlayed);
}
public static void main(String[] args) {
JFrame baseFrame = new JFrame();
Game gameObject = new Game();
gameObject.init();
baseFrame.setVisible(true);
baseFrame.getContentPane().add(gameObject);
}
}

Java applet buttons are not displayed until i hover the mouse over them

So My problem is that the applet lunches with nothing in it as soon as i hover the mouse
on top of the buttons it displays them and works perfectly afterwards. I think there might be something wrong with paint but i am not sure. I tried several changes but noting seems to work.
Any help will be much appreciated.
-- Rafael
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class poker extends JApplet implements ActionListener, ListSelectionListener {
private DefaultListModel listModel = new DefaultListModel();
JList jList = new JList(listModel);
JButton dealButton = new JButton("Deal");
JButton quitButton = new JButton("Quit");
JButton finishButton = new JButton("finish");
JPanel panel = new JPanel();
JPanel jPanel = new JPanel();
JPanel lPanel = new JPanel();
JLabel label = new JLabel();
JLabel balance = new JLabel();
private String displayDeal = null;
private String displayFinish = null;
private poker.Card deck[];
private int currentCard;
private double money = 0;
private poker.Card hand[];
private boolean nothing;
private boolean pair;
private boolean twoPair;
private boolean threeKind;
private boolean fourKind;
private boolean fullHouse;
private boolean flush;
private boolean straight;
private boolean royalStraight;
private boolean straightFlush;
private boolean RoyalFlush;
String faces[] = {"Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King", "Ace"};
String suits[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
#Override
public void init() {
this.setSize(500, 500);
this.setLayout(new BorderLayout());
jList.addListSelectionListener(this);
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
hand = new poker.Card[5];
deck = new poker.Card[52];
currentCard = -1;
for (int i = 0; i < deck.length; i++) {
deck[i] = new poker.Card(faces[i % 13], suits[i / 13]);
}
listModel.setSize(5);
dealButton.addActionListener(this);
finishButton.addActionListener(this);
quitButton.addActionListener(this);
finishButton.setEnabled(false);
panel.add(dealButton);
panel.add(finishButton);
panel.add(quitButton);
panel.add(label);
jPanel.add(jList);
add(balance, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
add(jPanel, BorderLayout.NORTH);
setVisible(true);
}
class Card {
#Override
public String toString() {
return face + " of " + suit + "\n";
}
public String getFace() {
return face;
}
public String getSuit() {
return suit;
}
private String face;
private String suit;
public Card(String s, String s1) {
face = s;
suit = s1;
}
}
#Override
public void valueChanged(ListSelectionEvent event) {
int[] indices = jList.getSelectedIndices();
if (indices.length > 4) {
JOptionPane.showMessageDialog(null, "You may only select four "
+ "cards.");
jList.clearSelection();
}
}
#Override
public void actionPerformed(ActionEvent event) {
poker.Card card = null;
if (event.getSource() == dealButton) {////////////////////////////
finishButton.setEnabled(true);
dealButton.setEnabled(false);
label.setText(null);
shuffle();// reset deck
for (int j = 0; j < 5; j++) {
card = dealCard();
hand[j] = card;
listModel.setElementAt(hand[j], j);
}
if (money < -1000) {
JOptionPane.showMessageDialog(null, "GAME OVER. You have no "
+ "more money. ");
System.exit(0);
}
//evaluate();
label.setText(displayDeal);
displayDeal = null;
} else if (event.getSource() == finishButton) {///////////////////////
dealButton.setEnabled(true);
finishButton.setEnabled(false);
int c = 5; //to get new card from deck
int maxIndex = jList.getMaxSelectionIndex();
for (int l = 0; l <= maxIndex; l++) {
if (jList.isSelectedIndex(l)) {
listModel.removeElementAt(l);
listModel.add(l, deck[c]);
c++;
}
}
jList.revalidate();
jPanel.repaint();
evaluate();
giveMoney();
label.setText(displayFinish);
balance.setHorizontalAlignment(SwingConstants.CENTER);
balance.setText("Money: $" + money );
jList.clearSelection();
displayFinish = null;
} else if (event.getSource() == quitButton) {///////////////////////
label.setText(null);
balance.setHorizontalAlignment(SwingConstants.CENTER);
balance.setText("You have won $" + money + " dollars.");
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit?", "User Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
dealButton.setEnabled(false);
finishButton.setEnabled(false);
quitButton.setEnabled(false);
System.exit(0);
}
}
this.setVisible(true);
this.validate();
}
// giveMoney() keeps track of the money.
public void giveMoney() {
if (nothing) {
money += -20.00;
nothing = false;
}
if (pair) {
money += 50.00;
pair = false;
}
if (twoPair) {
money += 100.00;
twoPair = false;
}
if (threeKind) {
money += 150.00;
threeKind = false;
}
if (straight) {
money += 200.00;
straight = false;
}
if (royalStraight) {
money += 200.00;
royalStraight = false;
}
if (flush) {
money += 250.00;
flush = false;
}
if (fullHouse) {
money += 300;
}
if (fourKind) {
money += 400.00;
fourKind = false;
}
if (straightFlush) {
money += 500.00;
straightFlush = false;
}
if (RoyalFlush) {
money += 1000.00;
RoyalFlush = false;
}
this.validate();
}
// populates deck array
public void shuffle() {
currentCard = -1;
for (int i = 0; i < deck.length; i++) {
int j = (int) (Math.random() * 52D);
poker.Card card = deck[i];
deck[i] = deck[j];
deck[j] = card;
}
this.validate();
}
public poker.Card dealCard() {
if (++currentCard < deck.length) {
return deck[currentCard];
} else {
dealButton.setEnabled(false);
return null;
}
}
public void evaluate() {
int i = 0;
String setOf = null;
nothing = false; pair = false; twoPair = false; threeKind = false;
straight = false; royalStraight = false; flush = false;
fullHouse = false; fourKind = false; straightFlush = false;
RoyalFlush = false;
if (hand[0].getSuit().equals(hand[1].getSuit())
&& hand[1].getSuit().equals(hand[2].getSuit())
&& hand[2].getSuit().equals(hand[3].getSuit())
&& hand[3].getSuit().equals(hand[4].getSuit())) {
flush = true;
displayDeal = "You have a flush";
displayFinish = "Flush. Win $250.00 dollars.";
}
if (sort2(hand) && !royalStraight) {
straight = true;
displayDeal = "You have a straight";
displayFinish = "Straight. Win $200.00 dollars.";
}
if (straight && flush) {
straightFlush = true;
straight = false;
flush = false;
displayDeal = "You have a straight Flush";
displayFinish = "straight Flush. Win $500.00 dollars.";
}
if (straightFlush) {
for (int j = 9; j < 13; j++) {
if (hand[i].getFace().equals(faces[j])
&& hand[i + 1].getFace().equals(faces[j])
&& hand[i + 2].getFace().equals(faces[j])
&& hand[i + 3].getFace().equals(faces[j])
&& hand[i + 4].getFace().equals(faces[j])) {
straightFlush = false;
RoyalFlush = true;
displayDeal = "You have a royal Flush";
displayFinish = "Royal Flush. Win $1000.00 dollars.";
}
}
}
if (straight) {
for (int j = 9; j < 13; j++) {
if (hand[i].getFace().equals(faces[j])
&& hand[i + 1].getFace().equals(faces[j])
&& hand[i + 2].getFace().equals(faces[j])
&& hand[i + 3].getFace().equals(faces[j])
&& hand[i + 4].getFace().equals(faces[j])) {
straight = false;
royalStraight = true;
displayDeal = "You have a royal straight";
displayFinish = "royal Straight. Win $200.00 dollars.";
}
}
}
if (hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[4].getFace())) {
fourKind = true;
displayDeal = "You have a four of a kind";
displayFinish = "Four of a kind. Win $400.00 dollars.";
} else if (hand[0].getFace().equals(hand[1].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[4].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[1].getFace().equals(hand[4].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace()) && !fullHouse) {
twoPair = true;
displayDeal = "You have two pairs. ";
displayFinish = "Two Pairs. Win $100.00 dollars.";
} else if (hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[2].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
&& hand[0].getFace().equals(hand[1].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace()) && !straightFlush) {
fullHouse = true;
displayDeal = "You have a full house.";
displayFinish = "Full House. Win $300.00 dollars.";
}
if ((hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[1].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[2].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[3].getFace()))
&& !twoPair && !fullHouse && !fourKind) {
threeKind = true;
displayDeal = "You have three of a kind of " + setOf + "s.";
displayFinish = "three of a kind of " + setOf + "s. Win $150.00 dollars.";
} else if ((hand[i].getFace().equals(hand[i + 1].getFace())
|| hand[i].getFace().equals(hand[i + 2].getFace())
|| hand[i].getFace().equals(hand[i + 3].getFace())
|| hand[i].getFace().equals(hand[i + 4].getFace())
|| hand[i + 1].getFace().equals(hand[i + 2].getFace())
|| hand[i + 1].getFace().equals(hand[i + 3].getFace())
|| hand[i + 1].getFace().equals(hand[i + 4].getFace())
|| hand[i + 2].getFace().equals(hand[i + 3].getFace())
|| hand[i + 2].getFace().equals(hand[i + 4].getFace())
|| hand[i + 3].getFace().equals(hand[4].getFace()))
&& !twoPair && !threeKind && !fullHouse) {
pair = true;
displayDeal = "You have a pair of " + setOf + "s.";
displayFinish = "Pair of " + setOf + "s. Win $50.00 dollars.";
}
if (!pair && !twoPair && !threeKind && !fullHouse && !fourKind
&& !straight && !flush && !straightFlush && !RoyalFlush
&& !royalStraight) {
nothing = true;
displayDeal = "You have nothing.";
displayFinish = "Nothing. Lose 20.00 dollars.";
}
this.validate();
}
public int getFaceValue2(poker.Card card) {
String s = card.getFace();
byte byte0 = 0;
if (s.equals(faces[0])) {
byte0 = 2;
}
if (s.equals(faces[1])) {
byte0 = 3;
}
if (s.equals(faces[2])) {
byte0 = 4;
}
if (s.equals(faces[3])) {
byte0 = 5;
}
if (s.equals(faces[4])) {
byte0 = 6;
}
if (s.equals(faces[5])) {
byte0 = 7;
}
if (s.equals(faces[6])) {
byte0 = 8;
}
if (s.equals(faces[7])) {
byte0 = 9;
}
if (s.equals(faces[8])) {
byte0 = 10;
}
if (s.equals(faces[9])) {
byte0 = 11;
}
if (s.equals(faces[10])) {
byte0 = 12;
}
if (s.equals(faces[11])) {
byte0 = 13;
}
if (s.equals(faces[12])) {
byte0 = 14;
}
return byte0;
}
public boolean sort2(poker.Card acard[]) {
boolean flag = false;
int ai[] = new int[5];
for (int i = 0; i < 5; i++) {
ai[i] = getFaceValue2(acard[i]);
}
for (int k = 1; k < ai.length; k++) {
for (int l = 0; l < ai.length - 1; l++) {
if (ai[l] > ai[l + 1]) {
int j = ai[l];
ai[l] = ai[l + 1];
ai[l + 1] = j;
}
}
}
for (int i1 = 0; i1 < ai.length - 1; i1++) {
if (ai[0] + 1 == ai[1] && ai[1] + 1 == ai[2] && ai[2] + 1
== ai[3] && ai[3] + 1 == ai[4]) {
flag = true;
} else {
flag = false;
}
}
if (flag) {
System.out.print(hand[0] + " " + hand[1] + " " + hand[2] + " "
+ hand[3] + " " + hand[4]);
}
System.out.print(ai[0] + " " + ai[1] + " " + ai[2] + " " + ai[3]
+ " " + ai[4]);
return flag;
}
}
When i run this applet using eclipse, it runs fine and i can see 2 buttons. Have you tried validating the applet after everything is ready?
this.validate();
this.repaint();
from Container.class:
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
I took sometime to modify the code of yours and I removed the paint() method and its working, now the screen display's without any freezing and all the components are displayed. Here's one important information for you which i found regarding paint() method when you extend JApplet.
Note: Move the logic which you had in your paint() method according to your design.
However, JApplets have a lot of extra structure that plain Applets
don't have. Because of this structure, the painting of a JApplet is a
more complex affair and is handled by the system. So, when you make a
subclass of JApplet you should not write a paint() method for it. As
we will see, if you want to draw on a JApplet, you should add a
component to the applet to be used for that purpose. On the other
hand, you can and generally should write an init() method for a
subclass of JApplet.
Below is the modified code, Hope it helps!!!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Poker extends JApplet implements ActionListener, ListSelectionListener {
private DefaultListModel listModel = new DefaultListModel();
JList jList = new JList(listModel);
JButton dealButton = new JButton("Deal card");
JButton quitButton = new JButton("Quit");
JButton finishButton = new JButton("finish");
JPanel panel = new JPanel();
JPanel jPanel = new JPanel();
private Poker.Card deck[];
private int currentCard;
private int money;
String faces[] = {
"Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Jack",
"Queen", "King", "Ace"
};
String suits[] = {
"Hearts", "Diamonds", "Clubs", "Spades"
};
private boolean card1State;
private boolean card2State;
private boolean card3State;
private boolean card4State;
private boolean card5State;
private Poker.Card hand[];
private boolean pressed;
private boolean nothing;
private boolean pair;
private boolean twoPair;
private boolean threeKind;
private boolean fourKind;
private boolean fullHouse;
private boolean flush;
private boolean straight;
private boolean royalStraight;
private boolean straightFlush;
private boolean RoyalFlush;
private final int ROYALFLUSH = 8;
private int value;
private boolean firstDeal;
#Override
public void init(){
this.setSize(500, 500);
jList.addListSelectionListener(this);
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
hand = new Poker.Card[5];
deck = new Poker.Card[52];
currentCard = -1;
for(int i = 0; i < deck.length; i++)
deck[i] = new Poker.Card(faces[i % 13], suits[i / 13]);
listModel.setSize(5);
dealButton.addActionListener(this);
finishButton.addActionListener(this);
quitButton.addActionListener(this);
finishButton.setEnabled(false);
// c.setLayout(new FlowLayout());
panel.add(dealButton);
panel.add(finishButton);
panel.add(quitButton);
add(panel, BorderLayout.SOUTH);
jPanel.add(jList);
add(jPanel, BorderLayout.NORTH);
setVisible(true);
}
class Card
{
#Override
public String toString()
{
return face + " of " + suit + "\n";
}
public String getFace()
{
return face;
}
public String getSuit()
{
return suit;
}
private String face;
private String suit;
public Card(String s, String s1)
{
face = s;
suit = s1;
}
}
#Override
public void valueChanged(ListSelectionEvent event) {
JList source = (JList) event.getSource();
java.util.List values = source.getSelectedValuesList();
listModel.removeElement(values);
changeCards();
}
#Override
public void actionPerformed(ActionEvent event) {
Poker.Card card = null;
int i = 5;
if(event.getSource() == dealButton){
pressed = true;
dealButton.setEnabled(false);
finishButton.setEnabled(true);
for(int j = 0; j < 5; j++){
card = dealCard();
hand[j] = card;
listModel.setElementAt(hand[j], j);
}
if(money < -1000){
JOptionPane.showMessageDialog(null, "GAME OVER. ");
System.exit(0);
}
}else if( event.getSource() == finishButton){
// still needs implementation
} else if (event.getSource() == quitButton) {
pressed = true;
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit?", "User Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
dealButton.setEnabled(false);
finishButton.setEnabled(false);
quitButton.setEnabled(false);
System.exit(0);
}
}
this.setVisible(true);
this.validate();
}
public void giveMoney() {
if (nothing)
{ money -= 20;
}
if (pair) {
money += 50;
}
if (twoPair) {
money += 100;
}
if (threeKind) {
money += 150;
}
if (straight) {
money += 200;
}
if (royalStraight)
{
money += 200;
}
if (flush) {
money += 250;
}
if (fullHouse) {
money += 300;
}
if (fourKind)
{
money += 400;
}
if (straightFlush) {
money += 500;
}
if (RoyalFlush) {
money += 1000;
}
}
public void shuffle() {
for (int i = 0; i < deck.length; i++) {
int j = (int) (Math.random() * 52D);
Poker.Card card = deck[i];
deck[i] = deck[j];
deck[j] = card;
}
dealButton.setEnabled(true);
this.validate();
}
public Poker.Card dealCard() {
if (++currentCard < deck.length) {
return deck[currentCard];
} else {
dealButton.setEnabled(false);
return null;
}
}
// public void paint(Graphics g){
//
// this.setBackground(Color.gray);
// Font font = new Font("Italic", 3, 14);
// g.setFont(font);
// if(pressed)
// {
// Font font1 = new Font("Card", 1, 24);
// g.setFont(font1);
//
// if(nothing)
// g.drawString("You got nothing!! You lose $20 ", 50, 125);
// if(pair)
// g.drawString("A pair!! Win $50 ", 50, 125);
// if(twoPair)
// g.drawString("Two pair!! win $100 ", 50, 125);
// if(threeKind)
// g.drawString("Three of a Kind!! Win $150 ", 50, 125);
// if(straight)
// g.drawString("A Straight!! Win $200 ", 50, 125);
// if (royalStraight)
// g.drawString("A Royal Straight!! Win $200 ", 50, 125);
// if(flush)
// g.drawString("A Flush!! Win $250 ", 50, 125);
// if(fullHouse)
// g.drawString("A Full House!! Win $300 ", 50, 125);
// if(straightFlush)
// g.drawString("A Straight Flush!! Win $500 ", 50, 125);
// if(RoyalFlush)
// g.drawString("A Royal Flush!! Win $100 ", 50, 125);
// }
//
// this.setVisible(true);
// }
public void changeCards(){
System.out.println("change cards");
firstDeal = true;
Object obj = null;
if(!card1State)
{
Poker.Card card = dealCard();
hand[0] = card;
}
if(!card2State)
{
Poker.Card card6 = dealCard();
hand[1] = card6;
}
if(!card3State)
{
Poker.Card card7 = dealCard();
hand[2] = card7;
}
if(!card4State)
{
Poker.Card card8 = dealCard();
hand[3] = card8;
}
if(!card5State)
{
Poker.Card card9 = dealCard();
hand[4] = card9;
}
}
public void evaluate() {
int i = 0;
if(hand[0].getSuit().equals(hand[1].getSuit()) &&
hand[1].getSuit().equals(hand[2].getSuit()) &&
hand[2].getSuit().equals(hand[3].getSuit()) &&
hand[3].getSuit().equals(hand[4].getSuit()))
{
flush = true;
if (flush == true)
System.out.println("you got a a flush");
}
if(sort2(hand)){
straight = true;
if (straight = true)
System.out.println("you got a a straight");
}
if(straight && flush)
{
straightFlush = true;
straight = false;
flush = false;
System.out.println("you got a straight flush");
}
if(straightFlush)
{
for(int j = 9; j < 13; j++)
if(hand[i].getFace().equals(faces[j]) &&
hand[i + 1].getFace().equals(faces[j + 1]) &&
hand[i + 2].getFace().equals(faces[j + 2]) &&
hand[i + 3].getFace().equals(faces[j + 3]) &&
hand[i + 4].getFace().equals(faces[j + 4]))
{
straightFlush = false;
RoyalFlush = true;
}
}
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()))
fourKind = true;
else
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[4].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[1].getFace().equals(hand[4].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) && !fullHouse)
{
System.out.println("2 pair=true;");
twoPair = true;
} else
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[2].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) &&
hand[0].getFace().equals(hand[1].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) && !straightFlush){
fullHouse = true;
}
if((hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[1].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[2].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[3].getFace())) &&
!twoPair && !fullHouse && !fourKind){
threeKind = true;
}
else
if((hand[i].getFace().equals(hand[i + 1].getFace()) ||
hand[i].getFace().equals(hand[i + 2].getFace()) ||
hand[i].getFace().equals(hand[i + 3].getFace()) ||
hand[i].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 2].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 3].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 2].getFace().equals(hand[i + 3].getFace()) ||
hand[i + 2].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 3].getFace().equals(hand[4].getFace())) &&
!twoPair && !threeKind && !fullHouse){
pair = true;
}
else
{ nothing = true;
System.out.println("you got nothing");
}
this.validate();
// giveMoney();
}
public int getFaceValue2( Poker.Card card) {
String s = card.getFace();
byte byte0 = 0;
if(s.equals(faces[0]))
byte0 = 2;
if(s.equals(faces[1]))
byte0 = 3;
if(s.equals(faces[2]))
byte0 = 4;
if(s.equals(faces[3]))
byte0 = 5;
if(s.equals(faces[4]))
byte0 = 6;
if(s.equals(faces[5]))
byte0 = 7;
if(s.equals(faces[6]))
byte0 = 8;
if(s.equals(faces[7]))
byte0 = 9;
if(s.equals(faces[8]))
byte0 = 10;
if(s.equals(faces[9]))
byte0 = 11;
if(s.equals(faces[10]))
byte0 = 12;
if(s.equals(faces[11]))
byte0 = 13;
if(s.equals(faces[12]))
byte0 = 14;
return byte0;
}
public boolean sort2( Poker.Card acard[]){
boolean flag = false;
int ai[] = new int[5];
for(int i = 0; i < 5; i++)
ai[i] = getFaceValue2(acard[i]);
for(int k = 1; k < ai.length; k++)
{
for(int l = 0; l < ai.length - 1; l++)
if(ai[l] > ai[l + 1])
{
int j = ai[l];
ai[l] = ai[l + 1];
ai[l + 1] = j;
}
}
for(int i1 = 0; i1 < ai.length - 1; i1++)
if(ai[0] + 1 == ai[1] && ai[1] + 1 == ai[2] && ai[2] + 1 ==
ai[3] && ai[3] + 1 == ai[4])
flag = true;
else
flag = false;
if(flag)
System.out.print(hand[0] + " " + hand[1] + " " + hand[2] + " " +
hand[3] + " " + hand[4]);
System.out.print(ai[0] + " " + ai[1] + " " + ai[2] + " " + ai[3] +
" " + ai[4]);
return flag;
}
}

Categories

Resources