简单计算器(java) (二)

2014-11-24 03:29:19 · 作者: · 浏览: 3
textfield.setText("");
}
}
last_in=key;
textfield.setText(textfield.getText()+buttonName);
}
else if(key=='+' || key=='-' || key=='*' || key=='/' || key=='='){
if(last_in>='0' && last_in<='9' || last_in=='='){
if(last_flag!=none){
tmp = new BigDecimal(textfield.getText());
switch(last_flag){
case '+':a=a.add(tmp);break;
case '-':a=a.subtract(tmp);break;
case '*':a=a.multiply(tmp);break;
case '/':
if(tmp.equals(zero)==true)textfield.setText("Error!");
else a=a.divide(tmp,6,BigDecimal.ROUND_HALF_UP);
break;
case '=':break;
}
last_flag=key;
textfield.setText(a.toString());
}
last_in=key;
}
}
/******************************************************************************/
}
}

public static void main(String args[]){

JFrame frm = new JFrame("计算器"); //创建窗体
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

hello fuck = new hello();
fuck.init();
frm.add("Center",fuck);
frm.pack();
frm.setLocation(250,250);
frm.setSize(200,230);

frm.setResizable(false);
frm.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.math.BigDecimal;
import javax.swing.JFrame;

public class hello extends Applet{
static int flag_A=0,flag_B=0;
static char none = 'n';
static char last_in=none; //最近一次合法输入
static char last_flag=none; //最近一次合法输入的运算符号
static BigDecimal a = BigDecimal.valueOf(0),tmp,zero = BigDecimal.valueOf(0);
static TextField textfield = new TextField();
SimpleListener ourListener = new SimpleListener();

protected void makebutton(String name,GridBagLayout gridbag,GridBagConstraints c){
Button button = new Button(name);
button.addActionListener(ourListener);
gridbag.setConstraints(button, c);
add(button);
}
public void init(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setFont(new Font("Helvetica",Font.BOLD,20));
setLayout(gridbag);

c.insets = new Insets(3,5,3,5);
c.gridheight = 1;
c.gridwidth = 4;
c.weightx = 1.5;
c.weighty = 1.5;
c.fill = GridBagConstraints.BOTH;

gridbag.setConstraints(textfield, c);
add(textfield);

/*button 和textfield 共用一个约束, www.2cto.com 只是textfield 占用一行四列空间*/
c.gri