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

时间:2013-08-22 19:03:54

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

任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:4)

您在这里看到了TextField#toString

的结果
ans.setText(ans.toString());

你想要

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

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

答案 1 :(得分:0)

ans是一个文本字段。您正在尝试将textfield对象转换为字符串,该字符串打印textfield的属性。尝试将numA转换为字符串。 (即Integer.toString(numA));