2013-08-22 78 views
0

我想创建一个简单的计算器来刷新我的技能。当我尝试设置的答案字段中的文本,而不是投入数或得到一个错误控制台,它把这个领域TextField.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(""); 
    } 
} 
} 

任何想法,将不胜感激。

回答

4

你看到的TextField#toString结果这里

ans.setText(ans.toString()); 

你想

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

你也可能需要使用Swing的JTextField一致性。

+0

Alrighty,会做感谢您的帮助C: –

+0

我只能说,回头看这我觉得有点傻 –

+0

'SO'见过傻的:) – Reimeus

0

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

+0

谢谢你的建议。我会牢记下C: –