What's wrong with this Java Applet code? [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to run this code in java applet via appletviewer in Fedora 18. But I get this error
java.lang.NullPointerException
at main.init(main.java:42)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:722)
As per my code 42nd line in my code is bMul.setBounds(100, 280, 50, 50); but this isn't wrong as-far-as i know. After searching on Google, I found that
NullPointerException is a runtime Exception thrown by the JVM when
your application code, other referenced API(s) or middleware
(Weblogic, WAS, JBoss...) encounters the following conditions:
Attempting to invoke an instance method of a null object
Attempting to access or modify a particular field of a null object
Attempting to obtain the length of such null object as an array
I've tried hard but failed in making it work. Please help me. Here I provide main.java file's code.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class main extends Applet implements ActionListener {
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;
Button bAdd, bSub, bMul, bDiv, bEqu, bCls, bDec, bSqrt, bSin, bCos, bTan;
TextField tf1;
int add, sub, mul, div, temp = 0;
double sqr, s, c, ta;
String t = "";
public void init() {
setLayout(null);
setFont(new Font("cantarell", Font.BOLD, 12));
b0 = new Button("0"); b1 = new Button("1");
b2 = new Button("2"); b3 = new Button("3");
b4 = new Button("4"); b5 = new Button("5");
b6 = new Button("6"); b7 = new Button("7");
b8 = new Button("8"); b9 = new Button("9");
bAdd = new Button("+"); bSub = new Button("-");
bSub = new Button("*"); bDiv = new Button("/");
bEqu = new Button("="); bSqrt = new Button("sqrt");
bSin = new Button("sin"); bCos = new Button("cos");
bTan = new Button("tan"); bCls = new Button("cls");
tf1 = new TextField("0");
tf1.setEditable(false);
tf1.setColumns(8);
tf1.setBounds(100, 100, 250, 50);
b0.setBounds(100, 130, 50, 50);
b1.setBounds(150, 130, 50, 50);
b2.setBounds(200, 130, 50, 50);
b3.setBounds(250, 130, 50, 50);
b4.setBounds(100, 180, 50, 50);
b5.setBounds(150, 180, 50, 50);
b6.setBounds(200, 180, 50, 50);
b7.setBounds(250, 180, 50, 50);
b8.setBounds(100, 230, 50, 50);
b3.setBounds(150, 230, 50, 50);
bAdd.setBounds(200, 230, 50, 50);
bSub.setBounds(250, 230, 50, 50);
bMul.setBounds(100, 280, 50, 50);
bDiv.setBounds(150, 280, 50, 50);
bEqu.setBounds(200, 280, 50, 50);
bSin.setBounds(300, 130, 50, 50);
bCos.setBounds(300, 180, 50, 50);
bTan.setBounds(300, 230, 50, 50);
bSqrt.setBounds(250, 280, 50, 50);
bCls.setBounds(300, 280, 50, 50);
add(b0); add(b1); add(b2);
add(b3); add(b4); add(b5);
add(b6); add(b7); add(b8); add(b9);
add(bAdd); add(bSub); add(bMul); add(bDiv);
add(bEqu); add(bSin); add(bCos); add(bTan);
add(bSqrt); add(bCls); add(tf1);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
bAdd.addActionListener(this);
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bEqu.addActionListener(this);
bSqrt.addActionListener(this);
bSin.addActionListener(this);
bCos.addActionListener(this);
bTan.addActionListener(this);
bCls.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == b0) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b0.getLabel());
else
tf1.setText(tf1.getText()+b0.getLabel());
temp = 0;
}
if(ae.getSource() == b1) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b1.getLabel());
else
tf1.setText(tf1.getText()+b1.getLabel());
temp = 0;
}
if(ae.getSource() == b2) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b2.getLabel());
else
tf1.setText(tf1.getText()+b2.getLabel());
temp = 0;
}
if(ae.getSource() == b3) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b3.getLabel());
else
tf1.setText(tf1.getText()+b3.getLabel());
temp = 0;
}
if(ae.getSource() == b4) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b4.getLabel());
else
tf1.setText(tf1.getText()+b4.getLabel());
temp = 0;
}
if(ae.getSource() == b5) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b5.getLabel());
else
tf1.setText(tf1.getText()+b5.getLabel());
temp = 0;
}
if(ae.getSource() == b6) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b6.getLabel());
else
tf1.setText(tf1.getText()+b6.getLabel());
temp = 0;
}
if(ae.getSource() == b7) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b7.getLabel());
else
tf1.setText(tf1.getText()+b7.getLabel());
temp = 0;
}
if(ae.getSource() == b8) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b8.getLabel());
else
tf1.setText(tf1.getText()+b8.getLabel());
temp = 0;
}
if(ae.getSource() == b9) {
zero();
if(tf1.getText().equals("0"))
tf1.setText(b9.getLabel());
else
tf1.setText(tf1.getText()+b9.getLabel());
temp = 0;
}
if(ae.getSource() == bSqrt) {
sqr = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.sqrt(sqr)));
}
if(ae.getSource() == bSin) {
s = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.sin(s)));
}
if(ae.getSource() == bCos) {
c = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.cos(c)));
}
if(ae.getSource() == bTan) {
ta = Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(Math.tan(ta)));
}
if(ae.getSource() == bAdd) {
add = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "+";
}
if(ae.getSource() == bSub) {
sub = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "-";
}
if(ae.getSource() == bMul) {
mul = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "*";
}
if(ae.getSource() == bDiv) {
div = Integer.parseInt(tf1.getText());
tf1.setText("");
t = "/";
}
if(ae.getSource() == bEqu) {
if(t == "+") {
int add1 = Integer.parseInt(tf1.getText());
int add2 = add + add1;
tf1.setText(String.valueOf(add2));
}
else if(t == "-") {
int sub1 = Integer.parseInt(tf1.getText());
int sub2 = sub - sub1;
tf1.setText(String.valueOf(sub2));
}
else if(t == "*") {
int mul1 = Integer.parseInt(tf1.getText());
int mul2 = mul * mul1;
tf1.setText(String.valueOf(mul2));
}
else if(t == "/") {
int div1 = Integer.parseInt(tf1.getText());
int div2 = div / div1;
tf1.setText(String.valueOf(div2));
}
if(temp == 0) temp = 1;
}
if(ae.getSource() == bCls)
tf1.setText("0");
if(ae.getSource() == bDec) {
String s = tf1.getText();
for(int i = 0; i < s.length(); i++) {
if((s.charAt(i)) == '.') break;
else tf1.setText(tf1.getText()+bDec.getLabel());
}
}
}
void zero() {
if(temp == 1) tf1.setText("0");
}
}

Look at these lines:
bAdd = new Button("+"); bSub = new Button("-");
bSub = new Button("*"); bDiv = new Button("/");
You're assigning a value to bSub twice, but not assigning any value to bMul, so it's still null.
When you then dereference bMul at line 42:
bMul.setBounds(100, 280, 50, 50);
... that's throwing a NullPointerException. I suspect the start of the second line from above should be:
bMul = new Button("*");
I would strongly advise you to stick to one statement per line. I'd also advise you to break your code up into smaller chunks - for example, one method to initialize the digits, another for the operators etc.

You didn't created the bMul object .
Just add this line bMul=new Button("*");

You didn't initialize bMul!! Thus you are referencing a null object and throw the exception

Related

Java coin toss score problem (score is multiplied instead of incremented)

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.

Infinite loop while comparing characters in a string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
What statement should I use to compare the characters in a string one by one so that it does not enter an infinite loop. Something like comparing an array of characters in C/C++.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Calcc extends JFrame implements ActionListener {
String l = "b";
int z = 0;
JFrame f;
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(10);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("0");
JButton b11 = new JButton("+");
JButton b12 = new JButton("-");
JButton b13 = new JButton("*");
JButton b14 = new JButton("/");
JButton b15 = new JButton("=");
Calcc() {
f = new JFrame();
f.add(t1);
f.add(t2);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(b10);
f.add(b11);
f.add(b12);
f.add(b13);
f.add(b14);
f.add(b15);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
f.setVisible(true);
f.setSize(350, 350);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String d;
d = t1.getText();
if (e.getSource() == b1) {
t1.setText(d + "1");
}
if (e.getSource() == b2) {
t1.setText(d + "2");
}
if (e.getSource() == b3) {
t1.setText(d + "3");
}
if (e.getSource() == b4) {
t1.setText(d + "4");
}
if (e.getSource() == b5) {
t1.setText(d + "5");
}
if (e.getSource() == b6) {
t1.setText(d + "6");
}
if (e.getSource() == b7) {
t1.setText(d + "7");
}
if (e.getSource() == b8) {
t1.setText(d + "8");
}
if (e.getSource() == b9) {
t1.setText(d + "9");
}
if (e.getSource() == b10) {
t1.setText(d + "0");
}
if (e.getSource() == b11) {
t1.setText(d + "+");
}
if (e.getSource() == b12) {
t1.setText(d + "-");
}
if (e.getSource() == b13) {
t1.setText(d + "*");
}
if (e.getSource() == b14) {
t1.setText(d + "/");
}
if (e.getSource() == b15) {
while (l != "a") {
int b = calcA(d);
if (l == "+")
z = z + b;
else if (l == "-")
z = z - b;
else if (l == "*")
z = z * b;
else if (l == "*")
z = z * b;
}
t2.setText(String.valueOf(z));
}
}
int calcA(String d1) {
l = "a";
int k = 0;
while ((d1 != "+") && (d1 != "-") && (d1 != "*") && (d1 != "/")) {
if (d1 != "\n")
break;
k = k * 10 + Integer.valueOf(d1);
}
l = d1;
return k;
}
}
public class CalcD {
public static void main(String[] args) {
new Calcc();
}
}
You appear to be comparing strings alot, using == to do it is bad practice.
This is because Strings are objects and comparing using the == operator will check to see if they are the exact same object regardless of value. Strings are a special case, when creating a String the jvm will decide whether or not to use an existing object or create a new one, so we can not be 100% sure if "==" will return true or not even the they contain the same value.
To compare Strings please use string1.equals(string2).
The .equals method should be used to compare the value of objects, and the == operator to compare primitives.
You do not need to check with any character like you do in C/C++. You need to simply iterate it with the length of the String. Simply use this in your loop:
for (int i=0;i<string.length();i++) {
char c = string.charAt(i);
// do whatever with your character.
}
That said, when you compare strings for equality in Java, you should always use the String.equals method instead of ==.
So, you should change your code from
getSource() == b1
to
getSource().equals(b1)
Hope this helps!
Thank you guys for clarifying some doubts....
for the above programme i used String.charAt(int);
to compare every specific character at the loop....

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!

Why doesn't boolean value switch?

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;
}

Binding keys to JButtons

I have a fairly simple Calculator and I am trying to bind keys to JButtons. I am new to Java and I don't know much. I do know it involves ActionListener but I can't wrap my head around how to get it into what I currently have.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class Calculator2 extends JFrame implements ActionListener {
// Declare the GUI objects and variables HERE
JTextField ansText;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, plus, minus, multi, div,
equal, clear;
JPanel p1, p2, p3;
Double val1 = 0.0, val2 = 0.0, answer = 0.0;
int operator = 0;
public static void main(String[] args) {
new Calculator2();
}
public Calculator2() {
// GUI Creation Code goes HERE
ansText = new JTextField("", 7);
ansText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
ansText.addKeyListener(new KeyAdapter() { //Allow only numbers in ansText
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume();
}
}
});
b1 = new JButton("1");
b1.addActionListener(this);
b2 = new JButton("2");
b2.addActionListener(this);
b3 = new JButton("3");
b3.addActionListener(this);
b4 = new JButton("4");
b4.addActionListener(this);
b5 = new JButton("5");
b5.addActionListener(this);
b6 = new JButton("6");
b6.addActionListener(this);
b7 = new JButton("7");
b7.addActionListener(this);
b8 = new JButton("8");
b8.addActionListener(this);
b9 = new JButton("9");
b9.addActionListener(this);
b0 = new JButton("0");
b0.addActionListener(this);
plus = new JButton("+");
plus.addActionListener(this);
minus = new JButton("-");
minus.addActionListener(this);
multi = new JButton("*");
multi.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
equal = new JButton("=");
equal.addActionListener(this);
clear = new JButton("C");
clear.addActionListener(this);
this.setLayout(new BorderLayout());
p1 = new JPanel();
this.add(p1, BorderLayout.NORTH);
p1.setLayout(new GridLayout(0, 1, 2, 2));
p1.add(ansText);
p2 = new JPanel();
this.add(p2, BorderLayout.CENTER);
p2.setLayout(new GridLayout(4, 3, 2, 2));
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(plus);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(minus);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(multi);
p2.add(clear);
p2.add(b0);
p2.add(equal);
p2.add(div);
this.setSize(200, 250);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//Number input
if (e.getSource() == b1) {
ansText.setText(ansText.getText() + b1.getText());
}
else if (e.getSource() == b2) {
ansText.setText(ansText.getText() + b2.getText());
}
else if (e.getSource() == b3) {
ansText.setText(ansText.getText() + b3.getText());
}
else if (e.getSource() == b4) {
ansText.setText(ansText.getText() + b4.getText());
}
else if (e.getSource() == b5) {
ansText.setText(ansText.getText() + b5.getText());
}
else if (e.getSource() == b6) {
ansText.setText(ansText.getText() + b6.getText());
}
else if (e.getSource() == b7) {
ansText.setText(ansText.getText() + b7.getText());
}
else if (e.getSource() == b8) {
ansText.setText(ansText.getText() + b8.getText());
}
else if (e.getSource() == b9) {
ansText.setText(ansText.getText() + b9.getText());
}
else if (e.getSource() == b0) {
ansText.setText(ansText.getText() + b0.getText());
}
//Operator input
else if (e.getSource() == plus) {
operator = 1;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == minus) {
operator = 2;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == multi) {
operator = 3;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
else if (e.getSource() == div) {
operator = 4;
val1 = Double.parseDouble(ansText.getText());
ansText.setText("");
}
//Misc
else if (e.getSource() == equal) {
val2 = Double.parseDouble(ansText.getText());
if (operator == 1) {
answer = val1 + val2;
ansText.setText("" + answer);
} else if (operator == 2) {
answer = val1 - val2;
ansText.setText("" + answer);
} else if (operator == 3) {
answer = val1 * val2;
ansText.setText("" + answer);
} else if (operator == 4) {
answer = val1 / val2;
ansText.setText("" + answer);
}
}
else if (e.getSource() == clear) {
ansText.setText("");
val1 = 0.0;
val2 = 0.0;
answer = 0.0;
operator = 0;
}
}
}
How to Use Key Bindings tutorial describes details of key bindings. Here is a simple example how to bind an action to a plus key both on the keypad and main keyboard:
JPanel panel = new JPanel();
JPanel panel = new JPanel();
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "plus");
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS,
InputEvent.SHIFT_MASK), "plus");
panel.getActionMap().put("plus", plusAction);
panel.add(button);
You do not want to have a single class with a few inner classes doing all your work. Java Swing, like most other GUI systems, is based on MVC, Model-View-Controller.
The Model here would be some object that contains the current value of the accumulator and the value being stored in the display. Were you writing a RPN calculator, the model object would contain the RPN stack.
The View would be the Swing classes: the JTextField, and the JButtons.
The Controller would be some new object, say CalculatorController, that does the actual work. Instead of your ActionListener adding, subtracting, multiplying, or dividing the numbers, they would call methods on your CalculatorController, and that object, in turn, would update the JTextField.
The suggestion by jedyobidan to look at Oracle's documentation is very good. You'd want to put the key strokes into the input map of the JPanel itself since they should apply no matter where in the panel the user has focused upon. The action maps would then hold AbstractActions that call methods on the CalculatorController.
I've always thought that the style of GUI development on the Mac or its predecessor NeXT, with their Interface Builder programs, is much better for novices than the style used by Java Swing.

Categories

Resources