java swing计算器(包括复制,粘贴与文件的打开与保存)

在这里插入代码片
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;

/**
 *
 * @author 你不及她
 */
   class myException extends Exception{
	 public myException() {
        super();
    }
    public myException(String msg){
    	super(msg);
        
    }
    }
public class FlowWindow extends JFrame implements ActionListener {
    private Frame f;
    private JTextField textField;
    private String result;
    private String ss=" ";
    private String jj=" ";
   
    private JMenuItem copy;
    private JMenuItem paste;
    private JMenuItem read;
    private Clipboard clipboard;
    private JButton s[]=new JButton[24];
    private JMenu m[]=new JMenu[5];//菜单
    private  JMenuItem about;
    private TextArea ta;
    private JMenuItem openItem, saveItem, closeItem;
     private FileDialog openDia, saveDia;
      private File file;
  public FlowWindow(){
      result="";
     this.setBackground(Color.LIGHT_GRAY);
       JPanel panel2=new JPanel();
       textField = new JTextField(30);
       textField.setEditable(false); 
     textField.setBackground(Color.GREEN);
      textField.setPreferredSize(new Dimension(200,50));

       this.add(textField, BorderLayout.NORTH);
        panel2.setLayout(new GridLayout(4,6,1,1));
      String []a={"←","C","0","+","-","*","1","2","3","/","%","D","4","5","6","√","^","Π","7","8","9",".","!","="};
      //JButton s[]=new JButton[24];
     for(int i=0;i<s.length;i++){
         s[i]=new JButton(a[i]);
        panel2.add(s[i]);
       s[i].addActionListener(new ButtonHandler1());
     }
     panel2.setBackground(Color.red);
     this.add(panel2,BorderLayout.CENTER);
     JMenuBar mb = new JMenuBar();
     String colors[]={"green","yellow","blue","red","orange","pink","gray"};
     String colors2[]={"green1","yellow1","blue1","red1","white1","pink1","gray1","orange1"};
        // 菜单
//        JMenu m[]=new JMenu[4];
         m[0] = new  JMenu("编辑");
       JMenuItem copy=new JMenuItem("复制");
       JMenuItem paste=new JMenuItem("粘贴");
  
      copy.addActionListener(new CopyListener());
      paste.addActionListener(new PasteListener());
   
       m[0].add(copy);
       m[0].add(paste);
   
         m[1] = new JMenu("设置");
        m[3] = new JMenu("帮助");
        m[2]=new JMenu("文件");
         openItem = new JMenuItem("打开");//创建"打开"菜单项
         saveItem = new JMenuItem("保存");//创建"保存"菜单项
         closeItem = new JMenuItem("退出");
         m[2].add(openItem);
         m[2].add(saveItem);
         m[2].add(closeItem);
            openDia = new FileDialog(this, "打开", FileDialog.LOAD);
         saveDia = new FileDialog(this, "保存", FileDialog.SAVE);
         myEvent();
       about=new JMenuItem("关于");
       m[3].add(about);
        about.addActionListener(this);
        JMenu color[]=new JMenu[2];
        JMenuItem m1[]=new JMenuItem[8];
        color[0]=new JMenu("按钮颜色");
        color[1]=new JMenu("text颜色");
        m[1].add(color[0]);
        m[1].add(color[1]);
        for(int i=0;i<6;i++){
        m1[i]=new JMenuItem(colors[i]);
        color[0].add( m1[i]);
        m1[i].addActionListener(new ButtonHandler2());
        }
         for(int i=0;i<8;i++){
        m1[i]=new JMenuItem(colors2[i]);
        color[1].add( m1[i]);
        m1[i].addActionListener(new ButtonHandler2());
        }
        mb.add(m[0]);
        mb.add(m[1]);
        mb.add(m[2]);
        mb.add(m[3]);
        
        // 把菜单栏加入到frame,这里用的是set而非add
        this.setJMenuBar(mb);
        clipboard= Toolkit.getDefaultToolkit().getSystemClipboard();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    
  }
  
class ButtonHandler1 implements ActionListener{//运算按钮监听
    public void actionPerformed(ActionEvent e){
        String s=e.getActionCommand();
       int a=0;
       int b=0;
       int c=0;//判断6++
       int d=0;//判断6.6.6
       if(s=="+"||s=="-"||s=="*"||s=="/"||s=="%"||s=="^"||s=="."){
//           System.out.println(result);
//          result=result;
//           System.out.println(result);
       ss=result.substring(result.length()-1, result.length());//记录当前最后一位
        System.out.println(ss);
//       if(result.length()>2){
//       jj=result.substring(result.length()-2,result.length()-1);//记录倒数第二位
//       System.out.println(jj);
//       }
       if(ss.equals("+")||ss.equals("-")||ss.equals("*")||ss.equals("/")||ss.equals("%")||ss.equals("^")||ss.equals(".")){  
       c=1;
       }
//       if(jj.equals(".")){
//        d=2;   
//       }
       }
    if(s.equals("C")) { 
      result=""; 
     d=0;
     }
    else if(s.equals("D")&&result.length()==1){
        result="1/"+result;
    }
//    else if(s.equals(".")&&(d==2)){
//        d=0;
//        System.out.println("error2");
//        
//        result=result.substring(0,result.length());
//    }
    else if ((s=="+"||s=="-"||s=="*"||s=="/"||s=="D"||s=="%"||s=="^"||s=="."||s=="!")&&(c==1)){
        System.out.println("error1");
        result=result.substring(0,result.length());
    }
    else if(s=="←"){
       b=result.length();
       result=result.substring(0,b-1);//删去字符串最后一位
     }
    else if(s.equals("=")) {                    //按下等号
            try{
                 result+= "="+calculate(result);
             }catch(myException ex) {
                    if(ex.getMessage().equals("被除数不能为0"))
                        result = ex.getMessage();
                    else
                        result = ex.getMessage();}
              textField.setText(result);
              a = 1;
              c=0;
              result="";
            }
     else{
                result +=s;   }     
    if(a==0){
                textField.setText(result);
        } }
   }
class ButtonHandler2 implements ActionListener{//设置按钮监听
    public void actionPerformed(ActionEvent e){
       String a=e.getActionCommand();
      switch(a){
          case "green1" : textField.setBackground(Color.green);break;
          case "yellow1": textField.setBackground(Color.yellow);break;
          case "blue1" :textField.setBackground(Color.blue);break;
           case "red1" : textField.setBackground(Color.red);break;
          case "white1": textField.setBackground(Color.white);break;
          case "gray1" :textField.setBackground(Color.gray);break;
           case "pink1" : textField.setBackground(Color.pink);break;
          case "orange1": textField.setBackground(Color.orange);break;
         
      }
       if(a.equals("green")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.green);
        }
       }
      if(a.equals("yellow")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.yellow);
        }
       }
       if(a.equals("blue")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.blue);
        }
       }
        if(a.equals("red")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.red);
        }
       }
         if(a.equals("gray")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.gray);
        }
       }
        if(a.equals("orange")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.orange);
        }
       } 
         if(a.equals("pink")){
        for(int i=0;i<24;i++) {
           s[i].setBackground(Color.pink);
        }
       }  
    }
    }
 
//编译按钮监听    加关于按钮监听
    public void actionPerformed(ActionEvent e){
        String s=e.getActionCommand();
      Object  source=e.getSource();
 
      if(source==about){
     // JOptionPane.showConfirmDialog(this, "软件1181张三 版权所有 侵权必究\n本计算器", "我的计算器", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE);  
              JOptionPane.showMessageDialog(this, "DC  Phoenix 版权所有 侵权必究", "我的计算器", JOptionPane.DEFAULT_OPTION);
        
//     
    }
    }
class CopyListener implements ActionListener { //拷贝数据处理
public void actionPerformed(ActionEvent event) {
StringSelection contents=new StringSelection(textField.getText()); //用拷贝文本框
//文本实例化StringSelection对象
clipboard.setContents(contents,null); //设置系统剪贴板内容
}}
class PasteListener implements ActionListener { //拷贝数据处理
public void actionPerformed(ActionEvent event) {
    Transferable contents= clipboard.getContents(this); //得到剪贴板内容
if(contents!=null &&contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
//判断内容是否为空,是否为字符串
try{
String string= (String) contents.getTransferData(DataFlavor.stringFlavor); 
//转换内容到字符串
textField.setText(string); //插入字符串到粘贴文本框
}catch (Exception ex){
ex.printStackTrace(); //错误处理
}}
 //设置系统剪贴板内容
}}
     private void myEvent()
     {
    	 //打开菜单项监听
    	 openItem.addActionListener(new ActionListener() {
    		public void actionPerformed(ActionEvent e)
    		{
    			openDia.setVisible(true); //显得打开文件对话框
    			String dirpath = openDia.getDirectory();//获取打开文件路径并且保存
    			String fileName = openDia.getFile();//获取文件名并且保存
    			
    			if(dirpath == null ||  fileName == null) //判断路径和文件是否为空
    				return ;
    			else 
    				textField.setText(null); //文件不为空 清楚原来文件内容
    			file = new File(dirpath, fileName); //创建新的路径和名称
    			try {InputStreamReader bu = new InputStreamReader(new FileInputStream(file), "UTF-8");

    				BufferedReader bufr = new BufferedReader(bu);//尝试从文件中读东西
    				String line = null; //变量字符串初始化为空
    				while((line = bufr.readLine())!= null)
                                    
    					textField.setText(line+"\r\n"); //显示每一行内容
    				bufr.close();//关闭文件
    				
    			}catch(FileNotFoundException e1) {
    				e1.printStackTrace(); // 抛出文件路径找不到异常
    			}catch(IOException e2){
    				e2.printStackTrace();// 抛出IO异常
    			}
    		}
    	 });
    	 
		saveItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (file == null) {
					saveDia.setVisible(true);//显示保存文件对话框
		    String dirpath = saveDia.getDirectory();//获取保存文件路径并保存到字符串中。
		    String fileName = saveDia.getFile();获取打保存文件名称并保存到字符串中
		  
		    if (dirpath == null || fileName == null)//判断路径和文件是否为空
		    	return;//空操作
		    else
		    	file=new File(dirpath,fileName);//文件不为空,新建一个路径和名称
			}
		    try {
		    	BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
		        String text = textField.getText();//获取文本内容
		        bufw.write(text);//将获取文本内容写入到字符输出流
		        bufw.close();//关闭文件
		    }catch (IOException e1) {
		    	e1.printStackTrace();//抛出IO异常
		    }
		}
		});
	    	 
    	 
    	 //窗体关闭监听
   
 
    	 //退出菜单项监听
    	 closeItem.addActionListener(new ActionListener() {
    		 public void actionPerformed(ActionEvent e)
    		 {
    			 System.exit(0);
    		 }
    	 });
     }



 public String calculate(String s)throws myException{
      char sign='+';
      double rea=0;
      double d=0;
      int top=0;
      int j=1;
      int c=0;
      double small=0;
      String result=" ";
      double temp=0;
      double [] stack=new double[s.length()];
      for(int i=0;i<s.length();i++){
          
          char ch=s.charAt(i);
          if((ch>='0'&&ch<='9')){
              d=(d*10.0-'0'+ch);
          }
          if(ch=='Π'){
              d=Math.PI;
          }
        if((i==s.length()-1)||(ch<'0'&&ch!=' ')||(ch=='^'||ch=='%'||ch=='√'||ch=='.'||ch=='D'||ch=='!')){
            if(sign=='+'){
               stack[++top]=+d;
            }
            if(sign=='-'){
                stack[++top]=-d;
            }
           if(sign=='^'){
                temp=Math.pow(stack[top],d);
               stack[top]=temp;
           }
          if(sign=='D'){
             temp=1/stack[top];
             stack[top]=temp;  
          }
          if(sign=='!'){
              for( int h=1;h<=stack[top];h++){
                 j*=h;
              }  
              stack[top]=j;
          }

          if(sign=='%'){
              temp=stack[top]%d;
              stack[top]=temp;
          }
            if(sign=='√'){
              temp=Math.sqrt(d);
              stack[top]=temp;
          }
           if(sign=='.'){
               if(d<10){
                   c=1;
               }
             if(d>10){
                 c=2;
             }
                small=Math.pow(0.1,c);
               temp=stack[top]+d*small;
               stack[top]=temp;
           }
           if(sign=='*'){
               temp=stack[top]*d;
               stack[top]=temp;
           }
           if(sign=='/'){
             if(d==0){
                 throw new myException("被除数不能为0");
             }
             else{
                 temp=stack[top]/d;
               stack[top]=temp;
             }
           }
            d=0.0;
            sign=ch;
      }  
      }
      while(top!=-1)
          rea+=stack[top--];
     if ((int)rea == rea)
               result=Integer.toString((int)rea);
            else 
                result=Double.toString(rea);
//      String result = String.valueOf(rea);
      return result;
   }

  public static void main(String[] args) { 
     FlowWindow jk=new FlowWindow();
       jk.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       jk.setVisible(true);
       jk.setTitle("计算器");
       jk.pack();
       jk.setBounds(500, 400, 500, 300);
      
} 
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Java Swing 计算器示例: ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Calculator extends JFrame implements ActionListener { // 创建界面组件 private JTextField textField; private JButton button0, button1, button2, button3, button4, button5, button6, button7, button8, button9; private JButton buttonAdd, buttonSubtract, buttonMultiply, buttonDivide, buttonEqual, buttonClear; // 记录计算结果和当前操作数 private double result = 0; private double currentNumber = 0; private String operator = ""; public Calculator() { // 设置窗口标题和大小 setTitle("Calculator"); setSize(300, 350); setResizable(false); // 创建界面组件 textField = new JTextField(); textField.setEditable(false); textField.setHorizontalAlignment(JTextField.RIGHT); button0 = new JButton("0"); button1 = new JButton("1"); button2 = new JButton("2"); button3 = new JButton("3"); button4 = new JButton("4"); button5 = new JButton("5"); button6 = new JButton("6"); button7 = new JButton("7"); button8 = new JButton("8"); button9 = new JButton("9"); buttonAdd = new JButton("+"); buttonSubtract = new JButton("-"); buttonMultiply = new JButton("*"); buttonDivide = new JButton("/"); buttonEqual = new JButton("="); buttonClear = new JButton("C"); // 设置组件位置和大小 textField.setBounds(10, 20, 270, 50); button7.setBounds(10, 80, 50, 50); button8.setBounds(70, 80, 50, 50); button9.setBounds(130, 80, 50, 50); buttonDivide.setBounds(190, 80, 50, 50); button4.setBounds(10, 140, 50, 50); button5.setBounds(70, 140, 50, 50); button6.setBounds(130, 140, 50, 50); buttonMultiply.setBounds(190, 140, 50, 50); button1.setBounds(10, 200, 50, 50); button2.setBounds(70, 200, 50, 50); button3.setBounds(130, 200, 50, 50); buttonSubtract.setBounds(190, 200, 50, 50); button0.setBounds(10, 260, 50, 50); buttonClear.setBounds(70, 260, 50, 50); buttonEqual.setBounds(130, 260, 50, 50); buttonAdd.setBounds(190, 260, 50, 50); // 添加组件到界面 add(textField); add(button7); add(button8); add(button9); add(buttonDivide); add(button4); add(button5); add(button6); add(buttonMultiply); add(button1); add(button2); add(button3); add(buttonSubtract); add(button0); add(buttonClear); add(buttonEqual); add(buttonAdd); // 添加事件监听器 button0.addActionListener(this); button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); button4.addActionListener(this); button5.addActionListener(this); button6.addActionListener(this); button7.addActionListener(this); button8.addActionListener(this); button9.addActionListener(this); buttonAdd.addActionListener(this); buttonSubtract.addActionListener(this); buttonMultiply.addActionListener(this); buttonDivide.addActionListener(this); buttonEqual.addActionListener(this); buttonClear.addActionListener(this); // 设置窗口可见性 setVisible(true); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("C")) { // 清空计算器 result = 0; currentNumber = 0; operator = ""; textField.setText(""); } else if (command.equals("+")) { // 加法 result += currentNumber; currentNumber = 0; operator = "+"; textField.setText(""); } else if (command.equals("-")) { // 减法 result -= currentNumber; currentNumber = 0; operator = "-"; textField.setText(""); } else if (command.equals("*")) { // 乘法 result *= currentNumber; currentNumber = 0; operator = "*"; textField.setText(""); } else if (command.equals("/")) { // 除法 if (currentNumber == 0) { textField.setText("Error"); } else { result /= currentNumber; currentNumber = 0; operator = "/"; textField.setText(""); } } else if (command.equals("=")) { // 等于号 if (operator.equals("+")) { result += currentNumber; } else if (operator.equals("-")) { result -= currentNumber; } else if (operator.equals("*")) { result *= currentNumber; } else if (operator.equals("/")) { if (currentNumber == 0) { textField.setText("Error"); } else { result /= currentNumber; } } currentNumber = result; operator = ""; textField.setText(Double.toString(result)); } else { // 数字键 currentNumber = currentNumber * 10 + Double.parseDouble(command); textField.setText(Double.toString(currentNumber)); } } public static void main(String[] args) { new Calculator(); } } ``` 这个计算器支持加、减、乘、除和清空操作,并且可以处理连续操作,例如 `1 + 2 - 3 * 4 / 5`。你可以根据需要进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值