根据我的代码,用户按下等于小程序后应该在文本字段中显示简化结果,但它没有这样做。
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="Calculator height=300 width=300 >
</applet>
*/
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Calculator extends Applet implements ActionListener{
Button b[]=new Button[10];
String tx="";
TextField field;
Button plus,minus,div,mul,equal;
public void init()
{
field=new TextField(12);
add(field);
for(int i=0;i<10;i++)
{
b[i]=new Button(String.valueOf(i));
add(b[i]);
b[i].addActionListener(this);
}
plus=new Button("+");
add(plus);
plus.addActionListener(this);
minus=new Button("-");
add(minus);
minus.addActionListener(this);
div=new Button("/");
add(div);
div.addActionListener(this);
mul=new Button("*");
add(mul);
mul.addActionListener(this);
equal=new Button("=");
add(equal);
equal.addActionListener(this);
}//end of init
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String msg=e.getActionCommand();
if(msg.equals("0")){
tx=tx+msg;
repaint();
}
if(msg.equals("1")){
tx=tx+msg;
repaint();
}
if(msg.equals("2")){
tx=tx+msg;
repaint();
}
if(msg.equals("3")){
tx=tx+msg;
repaint();
}
if(msg.equals("4")){
tx=tx+msg;
repaint();
}
if(msg.equals("5")){
tx=tx+msg;
repaint();
}
if(msg.equals("6")){
tx=tx+msg;
repaint();
}
if(msg.equals("7")){
tx=tx+msg;
repaint();
}
if(msg.equals("8")){
tx=tx+msg;
repaint();
}
if(msg.equals("+")){
tx=tx+msg;
repaint();
}
if(msg.equals("-")){
tx=tx+msg;
repaint();
}
if(msg.equals("*")){
tx=tx+msg;
repaint();
}
if(msg.equals("/")){
tx=tx+msg;
repaint();
}
if(msg.equals("=")){
calculate(tx);
}
}
public void paint(Graphics g){
field.setText(tx);
}
public void calculate(String tx){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object obj = null;
try {
obj = engine.eval(tx);
} catch (ScriptException ex) {
ex.printStackTrace();
}
tx=obj.toString();
repaint();
}
}