有些个bug目前还想不到怎么处理,欢迎板砖,欢迎鄙视~~
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 共用一个约束,只是textfield 占用一行四列空间*/
c.gridwidth = 1;
{"1","2","3","+"},
{"4","5","6","-"},
{"7","8","9","*"},
{".","0","=","/"}
};
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
c.gridx = j; c.gridy = i+1;
makebutton(button_name[i][j],gridbag,c);
}
}
}
private class SimpleListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String buttonName = e.getActionCommand();
char key = buttonName.charAt(0);
/******************************************************************************/
if(key=='.'){
if(textfield.getText().indexOf(".")==-1){
if(last_in!=none){
if(last_in=='+' || last_in=='-' || last_in=='*' || last_in=='/'){
last_flag=last_in;
a = new BigDecimal(textfield.getText());
textfield.setText("");
}
}
last_in=key;
textfield.setText(textfield.getText()+buttonName);
}
}
else if(key>='0' && key<='9'){
if(last_in!=none){
if(last_in=='='){
a = zero;
last_flag= none;
textfield.setText("");
}
else if(last_in=='+' || last_in=='-' || last_in=='*' || last_in=='/'){
last_flag=last_in;
a = new BigDecimal(textfield.getText());