gpt4 book ai didi

java - 简单计算器,其中创建了所有按钮并在 JButton 数组中添加了操作

转载 作者:行者123 更新时间:2023-12-01 12:09:22 25 4
gpt4 key购买 nike

我正在自学java初学者

我正在尝试使用 java swing 创建简单的计算器,我想创建 JButton 数组来创建项目中的所有按钮,我遇到了一些问题,所以我在构造函数之外声明了所有变量

public class SimpleCalculator extends JFrame implements ActionListener {
JButton btnArray[] = new JButton[16];
JLabel nameLabel = new JLabel("Ghanayem's Calculator",
SwingConstants.CENTER);
JTextField txt = new JTextField();
JPanel numPanel = new JPanel(new GridLayout(4, 3, 15, 5));
JPanel opPanel = new JPanel(new GridLayout(4, 1, 0, 5));
JPanel panel = new JPanel(new GridLayout(2, 1, 0, 5));
int counter;
char operation;
double operand1;
double operand2;

就像这样,我认为在 for 循环内向按钮添加操作不会出现编译器错误,一切都很好

for (counter = 0; counter < 10; counter++) {

btnArray[counter] = new JButton("" + counter);
btnArray[counter].addActionListener(this);
}

这是执行的操作

@Override
public void actionPerformed(ActionEvent e) {
txt.setText(txt.getText() + counter);
}

就像这样,当我尝试运行程序并按任何数字按钮时,添加到文本字段的数字对于所有按钮都是“16”,这是主要方法

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimpleCalculator frame = new SimpleCalculator();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

我快疯了,我不知道出了什么问题,请帮助我,这是我的第一个 Swing 应用程序,我很分散

谢谢

最佳答案

尝试这样的事情(我现在无法测试,因此它可能包含一些较小的错误):

@Override
public void actionPerformed(ActionEvent e) {
String value = ((JButton)e.getSource()).getText();
Integer intValue = Integer.parseInt(value);
Integer intValue2 = Integer.parseInt(txt.getText());
txt.setText( "" + (intValue + intValue2));
}

关于java - 简单计算器,其中创建了所有按钮并在 JButton 数组中添加了操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com