一个比较傻瓜的问题
要求编写一个模拟计算器的Applet,使用面板和网格布局,添加一个文本框,10个数字按钮(0~9),4个加减乘除按钮,一个等号按钮,一个清除按钮。要求将计算公式和结果显示在文本框当中。
其中数字按钮和清除按钮的事件好解决,但是4个加减乘除按钮,一个等号按钮的事件处理我不会,请高手指点,不胜感激。
------解决方案--------------------public class Calculator extends Applet implements ActionListener
{
private final String[] KEYS={ "7 ", "8 ", "9 ", "/ ",
"4 ", "5 ", "6 ", "* ",
"1 ", "2 ", "3 ", "- ",
". ", "0 ", "= ", "+ "};
private Button keys[]=new Button[KEYS.length];
private Button reset=new Button( "CE ");
private TextField display=new TextField( "0 ");
private void setup()
{
String s=new String();
Panel calkeys=new Panel();
calkeys.setLayout(new GridLayout(4,4));
for(int i=0; i <KEYS.length;i++)
{
keys[i]=new Button(KEYS[i]);
calkeys.add(keys[i]);
}
Panel top=new Panel();
top.setLayout(new BorderLayout());
top.add( "Center ",display);
top.add( "East ",reset);
setLayout(new BorderLayout());
add( "North ",top);
add( "Center ",calkeys);
}
public void init()
{
setup();
for(int i=0;i <KEYS.length;i++)
keys[i].addActionListener(this);
reset.addActionListener(this);
display.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object target=e.getSource();
String label=e.getActionCommand();
if(target==reset)
handleReset();
else if ( "0123456789. ".indexOf(label)> =0)
handleNumber(label);
else
handleOperator(label);
}
private boolean firstDigit=true;
private void handleNumber(String key)
{
if(firstDigit)
display.setText(key);
else if((key.equals( ". "))&&(display.getText().indexOf( ". ") <0))
display.setText(display.getText()+ ". ");
else if (!key.equals( ". "))
display.setText(display.getText()+key);
firstDigit=false;
}
private String operator= "= ";
private double number=0.0;
private void handleOperator(String key)
{
if(operator.equals( "+ "))
number+=getNumberFromDisplay();
else if(operator.equals( "- "))
number-=getNumberFromDisplay();
else if(operator.equals( "* "))
number-=getNumberFromDisplay();