I'm making a GUI calculator on Java. I've put in the actionlistener and buttons and stuff, and the buttons are being heard but whenever I press a number twice, double digits won't appear; only the second number will be shown. In my if statement, if an operation wasn't chosen (like + or -) then whatever number is pressed will be apart of the first number, like pressing 1 twice would make 11, not 1 and 1 separately - but that's what my calculator does anyway. If an operation is chosen then it will go to the second number. i haven't started my equal button yet but I want the numbers to form properly first. I cut down my code to two numbers so it's shorter on here. Thanks for anyone who helps!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.awt.FlowLayout;
public class CalculatorY {
public static JPanel panel = new JPanel(new GridLayout(5, 5));
public static JButton one, two, add;
public static JTextField result;
public static void main(String[] args) {
JFrame frame = new JFrame("calc");
result = new JTextField(null, 8);
one = new JButton("1");
two = new JButton("2");
add = new JButton("+");
add.addActionListener(new button());
one.addActionListener(new button());
two.addActionListener(new button());
panel.setLayout(new GridLayout(5, 5, 5, 25));
panel.setLayout(new FlowLayout());
panel.add(result);
panel.add(one);
panel.add(two);
panel.add(add);
frame.setVisible(true);
frame.setSize(200, 400);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
}
public static class button implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
String text = result.getText();
int textLength = text.length();
String letterValueOne = " ";
String letterValueTwo = " ";
String op = " ";
String valueOne;
switch (command) {
case "1":
if (op == " ") {
if (letterValueOne == " ") {
letterValueOne = "1";
System.out.println(letterValueOne);
} else {
letterValueOne = letterValueOne + 1;
}
} else {
if (letterValueOne != " " && letterValueTwo == " ") {
letterValueTwo = "1";
} else {
letterValueTwo = letterValueTwo + 1;
}
}
break;
case "2":
if (op == " ") {
if (letterValueOne == " ") {
letterValueOne = "2";
System.out.println(letterValueOne);
} else {
letterValueOne = letterValueOne + 2;
}
} else {
if (letterValueOne != " " && letterValueTwo == " ") {
letterValueTwo = "2";
} else {
letterValueTwo = letterValueTwo + 2;
}
}
break;
case "+":
System.out.println("+");
if (result == null) {
result = null;
} else if (letterValueOne != "") {
op = "+";
result.setText(letterValueOne + op);
} else if (letterValueOne != " " && letterValueTwo != " ") {
result.setText(letterValueOne + op + letterValueTwo);
op = "+";
}
break;
}
result.setText(letterValueOne + op + letterValueTwo);
}
}
}