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!
Related
My score in my JAVA coin toss program is multiplied instead of incremented and i have no idea why it's happening. I also know that i have some redundant code in this thing (ex. buttonsPanel.add(button2);
buttonsPanel.add(button); this.add(buttonsPanel); titlePanel.add(titleText); this.add(titlePanel); this.add(player_turn); this.add(playerOneScore); this.add(playerTwoScore); I will solve it after i find the solution to my score problem. )
Here is my code :
`
Random random = new Random();
int player1Score = 0;
int player2Score = 0;
JPanel buttonsPanel;
JButton button;
JButton button2;
JPanel titlePanel;
JLabel titleText;
JLabel player_turn;
JLabel playerOneScore;
JLabel playerTwoScore;
CoinToss(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Coin Toss test");
this.setSize(600,600);
this.setLayout(null);
this.getContentPane().setBackground(Color.black);
titlePanel = new JPanel();
titlePanel.setBackground(Color.blue);
titlePanel.setBounds(200, 10, 200, 40);
titleText = new JLabel();
titleText.setBackground(Color.blue);
titleText.setForeground(Color.yellow);
titleText.setFont(new Font("Ink Free",Font.ITALIC,25));
titleText.setHorizontalAlignment(JLabel.CENTER);
titleText.setText("Coin Toss Game");
titleText.setOpaque(true);
player_turn = new JLabel();
player_turn.setBounds(225, 200, 150, 50);
player_turn.setBackground(Color.blue);
player_turn.setForeground(Color.yellow);
player_turn.setFont(new Font("Ink Free",Font.ITALIC,25));
player_turn.setHorizontalAlignment(JLabel.CENTER);
player_turn.setText("Player1 turn");
player_turn.setOpaque(true);
buttonsPanel = new JPanel();
buttonsPanel.setBounds(200, 400, 200, 50);
buttonsPanel.setBackground(Color.blue);
button = new JButton("Tails");
button.setFocusable(false);
button.addActionListener(this);
button.setFont(new Font("Ink Free",Font.ITALIC,25));
button.setForeground(Color.green);
button2 = new JButton("Heads");
button2.addActionListener(this);
button2.setFocusable(false);
button2.setFont(new Font("Ink Free",Font.ITALIC,25));
button2.setForeground(Color.green);
playerOneScore = new JLabel();
playerOneScore.setBounds(50, 270, 210, 50);
playerOneScore.setBackground(Color.blue);
playerOneScore.setText("Player 1 score is : "+player1Score);
playerOneScore.setFont(new Font("Ink Free",Font.ITALIC,25));
playerOneScore.setOpaque(true);
playerTwoScore = new JLabel();
playerTwoScore.setBounds(350, 270, 210, 50);
playerTwoScore.setBackground(Color.blue);
playerTwoScore.setText("Player 2 score is : "+player2Score);
playerTwoScore.setFont(new Font("Ink Free",Font.ITALIC,25));
playerTwoScore.setOpaque(true);
buttonsPanel.add(button2);
buttonsPanel.add(button);
this.add(buttonsPanel);
titlePanel.add(titleText);
this.add(titlePanel);
this.add(player_turn);
this.add(playerOneScore);
this.add(playerTwoScore);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
int result = toss_coin(random);
if(e.getSource() == button2 ) {
if(result == 0) {
player1CorrectGuess();
updatePLayerTurn();
}
else {
player2IncorrectGuess(result);
updatePLayerTurn2();
}
}
else if(e.getSource() == button) {
if(result == 1) {
player1CorrectGuess();
updatePLayerTurn2();
}
else {
player2IncorrectGuess(result);
updatePLayerTurn();
}
}
WinRate();
}
static int toss_coin(Random random) {
int result = random.nextInt(2);
return result;
}
private void player1CorrectGuess() {
JOptionPane.showMessageDialog(null, "Correct. It's heads");
player1Score++;
playerOneScore.setText("Player 1 score is : "+player1Score);
}
private void player2IncorrectGuess(int result) {
JOptionPane.showMessageDialog(null, "Incorrect, the result was : " + (result == 0 ? "heads" : "tails") + ".");
player2Score++;
playerTwoScore.setText("Player 2 score is : "+player1Score);
}
private void updatePLayerTurn() {
player_turn.setText("Player2 turn");
}
private void updatePLayerTurn2() {
player_turn.setText("Player1 turn");
}
private void WinRate() {
int totalNumberOfSimulations = 20;
int numberOfWinsForPlayer1 = 0;
int numberOfWinsForPlayer2 = 0;
int maxScore = 10;
boolean turn_start = true;
for(int i=0;i<totalNumberOfSimulations;i++) {
player1Score = 0;
player2Score = 0;
while(player1Score < maxScore && player2Score < maxScore) {
int result = toss_coin(random);
if(turn_start) {
if(result == 0) {
player1Score++;
}
turn_start = false;
}
else {
if(result == 1) {
player2Score++;
}
turn_start = true;
}
if (player1Score == maxScore) {
numberOfWinsForPlayer1++;
}
else if(player2Score == maxScore) {
numberOfWinsForPlayer2++;
}
if (player1Score == maxScore && player2Score == maxScore) {
JOptionPane.showMessageDialog(null, "It's a tie, nobody wins.");
}
}
}
int winningChances = (numberOfWinsForPlayer1 * 100) / totalNumberOfSimulations;
int winningChances2 = (numberOfWinsForPlayer2 * 100) / totalNumberOfSimulations;
JOptionPane.showMessageDialog(null, "Player 1 winning chances: " + winningChances + "%"+"\nPlayer 2 winning chances: "+ winningChances2+ "%"); ;
//System.out.println("Player 1 winning chances: " + winningChances + "%");
//System.out.println("Player 2 winning chances: " + winningChances2 + "%");
}`
I tried getting help from chat GPT but that thing confused me even more.
I made a GUI program where it counts certain elements of whatever is entered in the main text field. If the text field is empty, a message should pop up saying that the user should enter text in the text field. I made an if statement if tfMain == null, a JOptionPane message should pop-up, but for some reason it won't. Any tips on why it doesn't pop up?
here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class LabExcer9 extends WindowAdapter implements ActionListener
{
//Container
private Frame f;
private Panel p1,p2,p3;
//Component
private Button bReadAndComp, bClear;
private TextField tfMain,tf1,tf2,tf3,tf4,tf5,tf6;
private Label l1,l2,l3,l4,l5,l6;
public LabExcer9()
{
f = new Frame("Character Counter of Miguel Martin");
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
bReadAndComp = new Button("Read and Compute");
bClear = new Button("Clear ALL Values");
tfMain = new TextField(null);
tf1 = new TextField("0");
tf2 = new TextField("0");
tf3 = new TextField("0");
tf4 = new TextField("0");
tf5 = new TextField("0");
tf6 = new TextField("0");
l1 = new Label("Number of Words ");
l2 = new Label("Number of Characters ");
l3 = new Label("Number of Vowels ");
l4 = new Label("Number of Consonants ");
l5 = new Label("Number of Digits ");
l6 = new Label("Number of Symbols and Spaces ");
}
public void assembleGUI()
{
p1.setLayout(new GridLayout(1,1));
p1.setPreferredSize(new Dimension(200, 200));
p1.add(tfMain);
p2.setLayout(new GridLayout(6,2));
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(l3);
p2.add(tf3);
p2.add(l4);
p2.add(tf4);
p2.add(l5);
p2.add(tf5);
p2.add(l6);
p2.add(tf6);
p3.setLayout(new GridLayout(1,2));
p3.add(bReadAndComp);
p3.add(bClear);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.CENTER);
f.add(p3,BorderLayout.SOUTH);
f.pack();
f.addWindowListener(this);
f.setVisible(true);
//registers
bReadAndComp.addActionListener(this);
bClear.addActionListener(this);
}
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
//gets main text
String textString = tfMain.getText();
//puts words into array
int vowels = 0, consonants = 0, digits = 0, symbolsAndSpaces = 0;
int characters = textString.length();
if(tfMain.getText() == "" || tfMain.getText() == null )
{
if(source == bReadAndComp)
JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if(tfMain.getText() != null && tfMain.getText() != "")
{
if(source == bReadAndComp)
{
for(int i = 0;i<textString.length();i++)
{
if(Character.isDigit(textString.charAt(i)))
digits++;
if(Character.isLetterOrDigit(textString.charAt(i)) == false)
symbolsAndSpaces++;
if(isVowel(textString.charAt(i)) == true)
vowels++;
else if(Character.isDigit(textString.charAt(i)) == false && isVowel(textString.charAt(i)) == false && textString.charAt(i) != ' ' && Character.isLetter(textString.charAt(i)) == true)
consonants++;
}
tf1.setText(""+textString.split(" ").length);
tf2.setText(""+characters);
tf3.setText(""+vowels);
tf4.setText(""+consonants);
tf5.setText(""+digits);
tf6.setText(""+symbolsAndSpaces);
//System.out.println(textStringArray[0]+"wat");
//JOptionPane.showMessageDialog(null, "Please Enter Text!");
}
else if (source == bClear)
{
tf1.setText("0");
tf2.setText("0");
tf3.setText("0");
tf4.setText("0");
tf5.setText("0");
tf6.setText("0");
tfMain.setText(null);
}
}
}
public boolean isVowel(char c)
{
if (c == 'a' || c == 'A' ||c== 'e' ||c == 'E' ||c == 'i' ||c == 'I' ||c == 'o' ||c == 'O' ||c == 'u' ||c == 'U')
return true;
else
return false;
}
public static void main(String args [])
{
LabExcer9 GUI = new LabExcer9();
GUI.assembleGUI();
}
}
To compare string please use equals or equalsIgnoreCase.
Replace your
if(tfMain.getText() == "" || tfMain.getText() == null )
statement with the following:
if("".equals(tfMain.getText())){
}
Ok guys...I'm stumped again.
I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.
Any pointers? (Code is copied below).
** A few other interesting bugs I feel worth mentioning:
1) Start and Reset don't seem to work correctly
2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.
package tictactoegame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TicTacToeBoard extends JFrame implements ActionListener
{
JButton[] buttons = new JButton[10];
boolean player1 = false, player2 = false;
boolean[] gameSquares = {false, false, false,
false, false, false,
false, false, false};
boolean startPlayer = false;
int turnCount = 0;
public TicTacToeBoard()
{
JFrame gameWindow = new JFrame();
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(300,400);
gameWindow.setVisible(true);
JPanel gamePanel = new JPanel();
gamePanel.setSize(300,400);
GridLayout grid = new GridLayout(4,3);
gamePanel.setLayout(grid);
for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JButton helpButton = new JButton("Help");
helpButton.addActionListener(this);
gamePanel.add(startButton);
gamePanel.add(helpButton);
gamePanel.add(resetButton);
gameWindow.add(gamePanel);
gameWindow.pack();
while (turnCount < 9)
{
gamePlay();
}
}
public void gamePlay()
{
while(!startPlayer)
{
int random = randomGenerator();
if (random%2 == 0)
{
player1 = true;
JOptionPane.showMessageDialog(null, "Player is first.");
startPlayer = true;
}
else if (random%2 == 1)
{
player2 = true;
JOptionPane.showMessageDialog(null, "Computer is first.");
startPlayer = true;
}
}
if (player2)
{
int index;
Random randomGenerator = new Random();
index = randomGenerator.nextInt(9);
buttons[index].doClick();
player2 = false;
player1 = true;
}
}
public int randomGenerator()
{
int randomNum;
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(100);
return randomNum;
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source instanceof JButton)
{
JButton button = (JButton) source;
if (button.getText() == "Start")
{
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Reset")
{
for(int i = 0; i < 9; i++)
{
buttons[i].setText("");
}
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Help")
{
JOptionPane.showMessageDialog(null, "Help:\n\n" +
"How to play-\n" +
"Select an empty square. The square will be filled with"
+ "with your symbole, either X or O.\n" +
"The game is won when either player gets three X's or"
+ "O's in a row horizontally,\n vertically, or diagonally.");
}
if (button.getText() == "" && player1)
{
button.setText("X");
turnCount += 1;
player1 = false;
player2 = true;
}
else if (button.getText() == "" && player2)
{
button.setText("O");
turnCount+=1;
player2 = false;
player1 = true;
}
else if (button.getText() == "X" || button.getText() == "O")
{
if(player2 == true)
{
gamePlay();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid choice. Select"
+ " another square.");
}
}
}
}
}
Check this TicTacToe Full code using the Applets...:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code="TicTacToe.class" width="300" height="300">
</applet>
*/
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();
public void init() {
CURRENT_PLAYER = PLAYER1;
lbl.setText(CURRENT_PLAYER + " Turn!");
setLayout(new BorderLayout());
Panel p = new Panel();
GridLayout gl = new GridLayout(3, 3);
p.setLayout(gl);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setSize(300, 300);
Font myFont = new Font("TimesRoman", Font.BOLD, 80);
for (int i = 0; i < 9; i++) {
btnarray[i] = new Button(null);
btnarray[i].setActionCommand("" + i);
btnarray[i].addActionListener(this);
btnarray[i].setFont(myFont);
btnarray[i].setBackground(Color.white);
p.add(btnarray[i]);
}
add(BorderLayout.CENTER, p);
add(BorderLayout.NORTH, lbl);
add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int index = Integer.parseInt(e.getActionCommand());
btnarray[index].disable();
if (CURRENT_PLAYER == PLAYER1) {
btnarray[index].setLabel("X");
CURRENT_PLAYER = PLAYER2;
} else {
btnarray[index].setLabel("0");
CURRENT_PLAYER = PLAYER1;
}
lbl.setText(CURRENT_PLAYER + " Turn!");
check();
}
void check() {
String[] pattern = new String[8];
pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
+ btnarray[2].getLabel();
pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
+ btnarray[5].getLabel();
pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
+ btnarray[8].getLabel();
pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
+ btnarray[6].getLabel();
pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
+ btnarray[7].getLabel();
pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
+ btnarray[8].getLabel();
pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
+ btnarray[8].getLabel();
pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
+ btnarray[6].getLabel();
int j = 0;
while (j < 8) {
char[] array = pattern[j].toCharArray();
if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
lbl.setText(PLAYER1 + " Wins!");
} else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
lbl.setText(PLAYER2 + " Wins!");
}
j++;
}
}
}
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.
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;
}