gpt4 book ai didi

java - TextField.setText() 返回一个奇怪的错误

转载 作者:行者123 更新时间:2023-12-01 18:44:30 27 4
gpt4 key购买 nike

我想创建一个简单的计算器来提高我的技能。当我尝试设置答案字段的文本时,它不会输入数字或在控制台中收到错误,而是将其放入字段中

java.awt.TextField[textfield0,356,6,52x23,invalid,text=,selection=0-0]

我以前从未遇到过这样的问题,所以我不太能想到原因。这是它的代码。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class aa extends JFrame implements ActionListener {

static TextField num1 = new TextField(3);
static TextField num2 = new TextField(3);
int numA = 0;
static TextField ans = new TextField(4);
JButton addB = new JButton("+");
JButton subB = new JButton("-");
JButton mulB = new JButton("*");
JButton divB = new JButton("%");

public static void main(String[] args) {
aa app =new aa();

}

public aa(){
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setSize(500, 400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel content = new JPanel();
this.setLayout(new FlowLayout());
this.add(num1);
this.add(num2);
this.add(addB);
addB.addActionListener(this);
this.add(subB);
subB.addActionListener(this);
this.add(mulB);
divB.addActionListener(this);
this.add(divB);
divB.addActionListener(this);
this.add(ans);
ans.setEditable(false);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.addB){
ans.setText("");
int x = Integer.parseInt(num1.getText());
int y = Integer.parseInt(num2.getText());
numA = x + y;
System.out.print(numA);
ans.setText(ans.toString());
}
if(e.getSource() == this.subB){
ans.setText("");
int x = Integer.parseInt(num1.getText());
int y = Integer.parseInt(num2.getText());
numA = x - y;
System.out.print(numA); //these parts were to make sure that it was actually doing the math, which it was.
ans.setText("");

}
if(e.getSource() == this.mulB){
ans.setText("");
}
}
}

任何想法将不胜感激。

最佳答案

您正在看到 TextField#toString 的结果这里

ans.setText(ans.toString());

你想要

ans.setText(Integer.toString(numA));

您可能还想使用 Swing 的 JTextField 来保持一致性。

关于java - TextField.setText() 返回一个奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18388838/

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