日期:2014-05-20  浏览次数:20615 次

在网上看见一个计算器的代码,结果有些不会,特开重分贴.顶着有分.特开重分贴.顶着有分.
import   java.awt.*;
import   java.awt.event.*;

class   Computer     implements   ActionListener
{
Frame   frame   =   new   Frame( "计算器   <羊子   工作室> ");
TextField   tf   =   new   TextField( "0 ");
int   state   =0;


public   Computer()
{
      Panel   panel   =   new   Panel();     //也是一个容器,但不能单独存在,最终要加到frame
      panel.setLayout(new   GridLayout(4,5));
      String   label[]   =   { "7 ", "8 ", "9 ", "/ ", "sqrt ", "4 ", "5 ", "6 ", "* ", "% ", "1 ", "2 ", "3 ", "- ", "1/x ", "0 ", "+/- ", ". ", "+ ", "= "};
      for(int   i=0;i <label.length;i++)
      {
        Button   b   =   new   Button(label[i]);
        if(label[i].equals( "/ ")||label[i].equals( "+ ")||label[i].equals( "- ")||label[i].equals( "* ")||label[i].equals( "= "))
        {
          b.setForeground(Color.red);
        }
        else
        {
          b.setForeground(Color.blue);
        }
        b.addActionListener(this);
        panel.add(b);
      }
      frame.setLocation(400,150);
      frame.add(tf, "North ");
      frame.add(panel, "Center ");

      frame.addWindowListener(new   WindowAdapter()
      {
        public   void   windowClosing(WindowEvent   e)
        {
          System.exit(0);
        }
      });
      frame.setSize(400,250);
      frame.setResizable(false);
      frame.setVisible(true);
}
int   a   =   0;
int   b   =   0;
int   c   =   0;
String   o   =   " ";

public   void   actionPerformed(ActionEvent   e)
{
    String   action   =   e.getActionCommand();     //所按按钮对应的标签值
    String   data_tf   =   tf.getText();     //文本框里的数字

    if(action.equals( "0 ")||action.equals( "1 ")||action.equals( "2 ")||action.equals( "3 ")||action.equals( "4 ")||action.equals( "5 ")
      ||action.equals( "6 ")||action.equals( "7 ")||action.equals( "8 ")||action.equals( "9 ")       )
    {
      if(state==0)
      {
        tf.setText(action);
        state   =   1;
      }
      else   if(state==1)
      {
        tf.setText(tf.getText()+action);