我在Java上制作GUI计算器。我已经放入了actionlistener和按钮和东西,按钮正在被听到,但每当我按两次数字时,都不会出现两位数;只会显示第二个数字。在我的if语句中,如果没有选择一个操作(如+或 - ),那么按下的任何数字都将是第一个数字的一部分,比如按1两次会产生11,而不是1和1分开 - 但这就是我的计算器无论如何。如果选择了一个操作,那么它将转到第二个数字。我还没有开始我的同等按钮,但我希望首先正确形成数字。我把我的代码减少到两个数字,所以它在这里更短。感谢任何帮助过的人!
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);
}
}
}