Java 返回奇数错误的TextField.setText()

Java 返回奇数错误的TextField.setText(),java,swing,numbers,jtextfield,settext,Java,Swing,Numbers,Jtextfield,Settext,我想创建一个简单的计算器来复习我的技能。当我尝试设置答案字段的文本时,它不会在控制台中输入数字或出现错误,而是将其放在字段中 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 e

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

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("");
    }
}
}

任何想法都将不胜感激

你在这里看到了结果

你想要

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

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

您可以在这里看到结果

你想要

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

您可能还想使用Swing的
JTextField
来保持一致性。
ans
是一个文本字段。您正在尝试将textfield对象转换为打印textfield属性的字符串。尝试将
numA
转换为字符串。(即
Integer.toString(numA))

ans
是一个文本字段。您正在尝试将textfield对象转换为打印textfield属性的字符串。尝试将
numA
转换为字符串。(即
Integer.toString(numA))
所以
看到了更愚蠢的:)
所以
看到了更愚蠢的:)