您的位置:首页 > 产品设计 > UI/UE

java-GUI小练习

2014-10-21 21:49 417 查看
package 计算器;

import java.awt.*;

import java.io.IOException.*;

import javax.swing.*;

import java.awt.event.*;

public class calculator extends JFrame implements ActionListener {

 

 private boolean newDigital=true;//判断输入是否为数

 private double d1;//第一个操作数

 private double d2;//第二个操作数

 private int optionValue=0;//表示加减运算符

 private int operation=1;

 

 JTextField w=new JTextField("输入表达式   ",15);

 JPanel p=new JPanel();

 JPanel p1=new JPanel();

 

 calculator()

 {

  this.setTitle("计算器");

  this.setLayout(new GridLayout(2,1));

  

  w.setHorizontalAlignment(JTextField.RIGHT);//设置文字右对齐

  p1.add(w);

  String[] J={"1","2","3","+","4","5","6","-","7","8","9","*",".","0","=","/"};

  for(int i=0;i<16;i++)

  {

   JButton j=new JButton(J[i]);

   j.addActionListener(this);

   p.add(j);

  }

  getContentPane().add(p1);

  getContentPane().add(p);

  p.setBackground(Color.blue);

  this.setSize(200,310);

  this.setVisible(true);

 }

 

 public void actionPerformed(ActionEvent e)

 {

  if(operation==0) w.setText("");//此处必须在最上方,否则不会清零,因为s已经得到值了

  String s=e.getActionCommand();//获取响应信息

  String str=w.getText();

  

  

  operation=1;

  if(s.equals("1")||s.equals("2")||s.equals("3")||s.equals("4")||s.equals("5")||s.equals("6")||s.equals("7")||s.equals("8")||s.equals("9")||s.equals("0"))

  {

   if(!newDigital) //判断是否为新输入数值

   {

    w.setText(str+s);

   }

   else

   {

    w.setText(s);

    newDigital=false;

   }

   return;

  }

  if(s.equals("."))//判断是否存在小数点

  {

   if(w.getText().indexOf(".")==-1)//如果不存在小数点 indexof()查找字符在串中第一次出现的位置的索引值

   {

    if(w.getText().trim().startsWith("0"))//判断是否以0开头,trim用于除去字符串开头和末尾的空格或其他字符,返回删除了字符串首尾去掉了空格符的串,出错时翻译空符(“”),无参数返回null

    {

     w.setText("0");

     newDigital=false;

    }

    else

    {

     w.setText(str+".");//设置标签中的字符串

    }

   }

   return;

  }

  if(s.equals("+"))

  {

   d1=Double.parseDouble(str.trim());//获取第一个操作数

   optionValue=1;

   w.setText("");//设置标签信息为空

   return;

  }

  if(s.equals("-"))

  {

   d1=Double.parseDouble(str.trim());

   optionValue=2;

   w.setText("");

  }

  if(s.equals("*"))

  {

   d1=Double.parseDouble(str.trim());

   optionValue=3;

   w.setText("");

  }

  

  if(s.equals("/"))

  {

   d1=Double.parseDouble(str.trim());

   optionValue=4;

   w.setText("");

  }

  

  if(s.equals("="))

  {

   operation=0;

   d2=Double.parseDouble(str.trim());

   switch(optionValue)

   {

   case 1:

    w.setText(String.valueOf(d1+d2));//valueof()将其转换为字符串

    break;

   case 2:

    w.setText(String.valueOf(d1-d2));

    break;

   case 3:

    w.setText(String.valueOf(d1*d2));

    break;

   

   case 4:

    if(d2!=0)

    w.setText(String.valueOf(d1/d2));

    else w.setText("error,unexpected 0");

    break;

   

   }

   

  }

  

  

 }

 

 public static void main(String[] args)

 {

  new calculator();

 

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: