0

I wanted to create a simple calculator to brush up on my skills. When I try to set the text for the answer field, instead of putting in a number or getting an error in the console, it puts this in the field

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

I've never had such a problem before, so I can't quite think of the cause. Here is the code for it.

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

Any ideas would be appreciated.

4

2 回答 2

4

你看到TextField#toString这里的结果

ans.setText(ans.toString());

你要

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

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

于 2013-08-22T19:05:44.790 回答
0

The ans is a textfield. You are trying to convert a textfield object into string which prints the properties of textfield. Try to convert numA to string. (i.e Integer.toString(numA));

于 2013-08-22T19:23:53.663 回答