一个计算器的计算方法的问题
代码如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameCalculator{
public static void main(String args[]){
JFrameCalculatorClass JFC=new JFrameCalculatorClass();
JFC.CalculatorDisplay();
}
}
class JFrameCalculatorClass extends JFrame{
double result;
boolean start;
String lastStrMethod;
Container container=getContentPane();
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTextField txtField=new JTextField( "0 ",24);
JButton []btn=new JButton[11];
ActionListener btnNumAction=new NumberCountAction();
ActionListener CountMethod=new CountMethodClass();
//构造函数
JFrameCalculatorClass(){
result=0;
start=true;
lastStrMethod= "= ";
p1.add(txtField);
btn[0]=new JButton( "1 ");
btn[1]=new JButton( "2 ");
btn[2]=new JButton( "3 ");
btn[3]=new JButton( "4 ");
btn[4]=new JButton( "5 ");
btn[5]=new JButton( "6 ");
btn[6]=new JButton( "7 ");
btn[7]=new JButton( "8 ");
btn[8]=new JButton( "9 ");
btn[9]=new JButton( "0 ");
btn[10]=new JButton( ". ");
p2.setLayout(new GridLayout(4,3,7,7));
for(int i=0;i <11;i++){
btn[i].addActionListener(btnNumAction);
p2.add(btn[i]);
}
addButton( "+ ",CountMethod);
addButton( "- ",CountMethod);
addButton( "* ",CountMethod);
addButton( "/ ",CountMethod);
addButton( "= ",CountMethod);
}
//实例化数字按键
void addButton(String method,ActionListener listener){
JButton btn=new JButton(method);
btn.addActionListener(listener);
p3.add(btn);
}
//构建窗体
public void CalculatorDisplay(){
container.add(new JLabel( " "),BorderLayout.WEST);
container.add(new JLabel( " "),BorderLayout.EAST);
container.add(p1,BorderLayout.NORTH);
container.add(p2,BorderLayout.CENTER);
container.add(p3,BorderLayout.SOUTH);
setSize(300,250);
setLocation(250,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
//获得文本框内的数据
class NumberCountAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String input=e.getActionCommand();
if(start){
txtField.setText( " ");
start=false;
}
txtField.setText(txtField.getText()+input);
}
}
//设置文本框输入符号
class CountMethodClass implements ActionListener{
public void actionPerformed(ActionEvent e){
String strMethod=e.getActionCommand();
if(start){
if(strMethod.equals( "- ")){
txtField.setText(strMethod);
start=false;
}else{
lastStrMethod=strMethod;
}
}else{
Calculate(Double.parseDouble(txtField.getText()));
lastStrMethod=strMethod;
start=true;