一个奇怪的问题(setText()无法再文本框中显示内容)
程序代码:
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator extends JFrame{ private JButton[] btn = new JButton[16]; private JButton CE = new JButton(); private JPanel p1 = new JPanel(); private JPanel p2 = new JPanel(); private JTextField txt = new JTextField("0"); String A = new String();//表达式里的数字 int a,result = 0; public Calculator(){ this.setLayout(new BorderLayout(0,20)); for(int i = 0; i <= 9; i++){ btn[i] = new JButton(String.valueOf(i)); //整型转化为字符串 // System.out.println(a+""); // System.out.println(String.valueOf(a)); // System.out.println(((Integer)a).toString()); } btn[10] = new JButton(String.valueOf("+")); btn[11] = new JButton(String.valueOf("-")); btn[12] = new JButton(String.valueOf("*")); btn[13] = new JButton(String.valueOf("/")); btn[14] = new JButton(String.valueOf("=")); btn[15] = new JButton(String.valueOf("清空")); p1.setLayout(new GridLayout(4,4,10,30)); this.add(txt,BorderLayout.NORTH); OperatorHandle oh = new OperatorHandle(); for(int j = 0; j < 16; j++){ p1.add(btn[j]); btn[j].addActionListener(oh); } //System.out.println("A="+A); txt.setSize(60, 40); this.add(p1,BorderLayout.CENTER); this.setBounds(100, 200, 300, 350); } public static void main(String[] args) { Calculator f =new Calculator(); f.setVisible(true); } class OperatorHandle implements ActionListener{ String s;//监听器类:每次点击下按钮产生的操作,只是重复执行的 actionperformed函数,其在类中定义的变量如 string s;只会执行一次 String oprate = "$"; @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String cmd=e.getActionCommand(); int idx= "0123456789".indexOf(cmd); System.out.println("idx="+idx); if (idx!=-1){//is number s = "0123456789".substring(idx,idx+1); A += s; a = Integer.parseInt(A); System.out.println("a="+a+ " A="+A+" result="+result); txt.setText(A); if(!oprate.equals("$")){ switch(oprate){ case "+": result += a; break; case "-": result -= a; break; case "*": result *= a; break; case "/": result /= a; break; } } txt.setText(String.valueOf(result)); System.out.println("result="+result); } else{// is oprate int x = "+-*/".indexOf(cmd); System.out.println("a="+a+" x="+x+" result="+result); switch(x){ case 0: oprate = "+"; break; case 1: oprate = "-"; break; case 2: oprate = "*"; break; case 3: oprate = "/"; break; } result = Integer.parseInt(A); A = "0"; //txt.setText(String.valueOf(result)); } } } }