Posted on 2006-10-12 10:09
my 阅读(385)
评论(0) 编辑 收藏 所属分类:
java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame implements ActionListener
{
private JButton ButtonNum[]=new JButton[16];
private String countCode[]={"/","*","-","+","=","."};
private JTextField displayField=new JTextField();
private JPanel pan=new JPanel();
private String displayStr="";
private double firstNum=0,secondNum=0;
private int countNum;
private boolean start=false,end=false;
public MyFrame()
{
super("模拟简便计算器");
setSize(400,400);
Container c=getContentPane();
c.setLayout(new BorderLayout());
displayField.setHorizontalAlignment(JTextField.RIGHT);
displayField.setFont(new Font("TimesRoman",Font.BOLD,50));
displayField.setBackground(Color.gray);
displayField.setEditable(false);
displayField.addActionListener(this);
c.add(displayField,"North");
c.add(pan,"Center");
pan.setLayout(new GridLayout(4,4));
for(int n=0;n<16;n++) //定义按键属性
{
if(n<10)
{
ButtonNum[n]=new JButton(n+"");
ButtonNum[n].setFont(new Font("TimesRoman",Font.BOLD,50));
ButtonNum[n].setBackground(Color.lightGray);
ButtonNum[n].addActionListener(this);
pan.add(ButtonNum[n]);
}
else
{
ButtonNum[n]=new JButton(countCode[15-n]);
ButtonNum[n].setFont(new Font("TimesRoman",Font.BOLD,50));
ButtonNum[n].addActionListener(this);
pan.add(ButtonNum[n]);
}
}
setVisible(true);
}
public static void main(String args[])
{
MyFrame myFrame=new MyFrame();
}
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
public void actionPerformed(ActionEvent e)
{
for(int i=0;i<16;i++)
{
if(i<=10) //算数按钮输入事件处理 判断并显示输入的运算数字
{
if(e.getSource()==ButtonNum[i] && start==false)
{
displayStr=displayStr+ButtonNum[i].getLabel();
displayField.setText(displayStr);
}
if(e.getSource()==ButtonNum[i] && start==true)
{
displayStr=displayStr+ButtonNum[i].getLabel();
displayField.setText(displayStr);
end=true;
}
}
if(i>=12 && i<=15) //运算按钮事件处理 判断并接受输入的运算数字
{
if(e.getSource()==ButtonNum[i] && start==false)
{
firstNum=Double.valueOf(displayField.getText()).doubleValue();
countNum=i;
displayField.setText("");
displayStr="";
start=true;
}
else
{ if(e.getSource()==ButtonNum[i] )
{
countNum=0;
displayField.setText("");
displayStr="";
firstNum=0;
secondNum=0;
end=false;
}
}
}
if(e.getSource()==ButtonNum[11]) //等号按钮事件处理
{
secondNum=Double.valueOf(displayField.getText()).doubleValue();
if(start=true && end==true)
{
if(countNum==12)
displayField.setText(firstNum+secondNum+"");
if(countNum==13)
displayField.setText(firstNum-secondNum+"");
if(countNum==14)
displayField.setText(firstNum*secondNum+"");
if(countNum==15 && secondNum!=0)
displayField.setText(firstNum/secondNum+"");
}
countNum=0;
displayStr="";
firstNum=0;
secondNum=0;
start=false;
end=false;
}
}
}
}