仿windows的java计算器

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener{
    private static final long serialVersionUID = 1L;
    private JButton[] btn;
    private String[] labels = {"MC","MR","MS","M+","M-",
            "←","CE","C","±","√",
            "7","8","9","/","%",
            "4","5","6","*","1/x",
            "1","2","3","-","=",
            "0",".","+"};
    private double d1 = 0.0, d2 = 0.0;
    private String opt = "操作符";
    private JTextArea result = new JTextArea("0",3,20);

    public Calculator(String title)
    {
        super(title);
        this.setVisible(true);
        this.setBounds(400, 300, 200, 350);
        result.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        addMenu();

        btn = new JButton[28];
        for(int i=0;i<btn.length;i++)
        {
            btn[i] = new JButton(labels[i]);
        }        

        this.add(result, BorderLayout.NORTH);
        Panel p = new Panel();
        p.setLayout(new GridLayout(3,1));

        Panel p1 = new Panel();
        p1.setLayout(new GridLayout(2,5,2,2));
        for(int i=0;i<10;i++)
        {
            p1.add(btn[i]);
        }
        Panel p2 = new Panel();
        p2.setLayout(new GridLayout(2,5,2,2));
        for(int i=10;i<20;i++)
        {
            p2.add(btn[i]);
        }
        Panel p3 = new Panel();
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        p3.setLayout(gridbag);
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(1,1,0,0);

        c.weightx = 1.0;
        addButton(p3,btn[20],gridbag,c);
        addButton(p3,btn[21],gridbag,c);
        addButton(p3,btn[22],gridbag,c);
        addButton(p3,btn[23],gridbag,c);

        c.gridwidth =GridBagConstraints.REMAINDER;
        c.gridheight=2;
        addButton(p3,btn[24],gridbag,c);

        //0
        c.gridx = 0;
        c.gridwidth=2;
        c.gridheight=1;
        addButton(p3,btn[25],gridbag,c);

        c.gridx=2;
        c.gridwidth=1;
        c.gridheight=1;
        addButton(p3,btn[26],gridbag,c);
        //+
        c.gridx=3;
        c.gridwidth=1;
        c.gridheight=1;
        addButton(p3,btn[27],gridbag,c);

        p.add(p1);
        p.add(p2);
        p.add(p3);
        this.add(p,BorderLayout.CENTER);

        this.pack();
        this.setResizable(false);

        //for(int i=0;i<28;i++)
        //    System.out.println("btn["+i+"]: "+btn[i].getActionCommand());
        for(int i=0;i<28;i++)
            btn[i].addActionListener(this);

        //关闭窗口
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }

    public void addMenu()
    {

        JMenuBar mb = new JMenuBar();
        //查看
        JMenu viewMenu = new JMenu("查看(V)");
        viewMenu.setMnemonic(‘V‘);
        JMenuItem stardardItem = new JMenuItem("标准型");
        JMenuItem scienceItem = new JMenuItem("科学型");
        JMenuItem digitalItem = new JMenuItem("数字统计");
        JMenuItem basicItem = new JMenuItem("基本");

        //编辑
        JMenu editMenu = new JMenu("编辑(E)");
        editMenu.setMnemonic(‘E‘);
        final JMenuItem copyItem = new JMenuItem("复制(C)");
        copyItem.setAccelerator(KeyStroke.getKeyStroke(‘C‘,InputEvent.CTRL_MASK));
        copyItem.setMnemonic(‘C‘);
        copyItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                result.selectAll();
                result.copy();
            }
        });
        final JMenuItem pasteItem = new JMenuItem("粘贴(V)");
        pasteItem.setAccelerator(KeyStroke.getKeyStroke(‘V‘,InputEvent.CTRL_MASK));
        pasteItem.setMnemonic(‘V‘);
        pasteItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                result.paste();
            }
        });

        final JMenuItem cutItem = new JMenuItem("剪切(X)");
        cutItem.setAccelerator(KeyStroke.getKeyStroke(‘X‘,InputEvent.CTRL_MASK));
        cutItem.setMnemonic(‘X‘);
        cutItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                result.selectAll();
                result.cut();
            }
        });

        //帮助
        JMenu helpMenu = new JMenu("帮助(H)");
        helpMenu.setMnemonic(‘H‘);
        JMenuItem viewHelpItem = new JMenuItem("查看帮助");
        JMenuItem aboutItem = new JMenuItem("关于计算器");

        //添加菜单项
        viewMenu.add(stardardItem);
        viewMenu.add(scienceItem);
        viewMenu.addSeparator();
        viewMenu.add(digitalItem);
        viewMenu.addSeparator();
        viewMenu.add(basicItem);

        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        editMenu.add(cutItem);

        helpMenu.add(viewHelpItem);
        helpMenu.addSeparator();
        helpMenu.add(aboutItem);

        //添加菜单
        mb.add(viewMenu);
        mb.add(editMenu);
        mb.add(helpMenu);

        final JPopupMenu pm = new JPopupMenu();
        pm.add(copyItem);
        pm.add(pasteItem);
        pm.add(cutItem);
        result.addMouseListener(new MouseAdapter()
        {
            public void mouseReleased(MouseEvent e)
            {
                if(e.isPopupTrigger())
                    pm.show(result,e.getX(),e.getY());
            }
        });
        result.add(pm);
        this.setJMenuBar(mb);
    }

    public void addButton(Panel p,JButton btn,GridBagLayout g, GridBagConstraints c)
    {
        g.setConstraints(btn, c);
        p.add(btn);
    }

    public static void main(String[] args) {
        new Calculator("Java 计算器");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object t = e.getSource();
        try{
            //0-9的数字按钮
            for(int i=25;i<26;i++)
                if(t.equals(btn[i]))
                    result.setText(result.getText()+(i-25));//0
            for(int i=20;i<23;i++)
                if(t.equals(btn[i]))
                    result.setText(result.getText()+(i-19));//1 2 3
            for(int i=15;i<18;i++)
                if(t.equals(btn[i]))
                    result.setText(result.getText()+(i-11));//4 5 6
            for(int i=10;i<13;i++)
                if(t.equals(btn[i]))
                    result.setText(result.getText()+(i-3));// 7 8 9
            //加法+
            if(t.equals(btn[27]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "+";
            }

            //减法-
            if(t.equals(btn[23]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "-";
            }

            //乘法*
            if(t.equals(btn[18]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                result.setText("");
                opt = "*";
            }

            //除法/
            if(t.equals(btn[13]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "/";
            }
            //取模
            if(t.equals(btn[14]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "%";
            }
            //四则运算、取模结果
            if(t.equals(btn[24]))
            {
                d2 = Double.parseDouble(result.getText());
                System.out.println(d2);
                //result.setText("");
                if(opt.equals("+"))
                    result.setText(""+(d1+d2));
                else if(opt.equals("-"))
                    result.setText(""+(d1-d2));
                else if(opt.equals("*"))
                    result.setText(""+(d1*d2));
                else if(opt.equals("/"))
                {
                    if(d2 == 0)
                        result.setText("除数不能为0");
                    else
                        result.setText(""+(d1/d2));
                }
                else if(opt.equals("%"))
                    result.setText(""+(d1%d2));
            }
            //求导
            if(t.equals(btn[19]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "1/x";
                if(opt.equals("1/x"))
                    result.setText(""+(1/d1));
            }
            //开方
            if(t.equals(btn[9]))
            {
                d1 = Double.parseDouble(result.getText());
                System.out.println(d1);
                opt = "√";
                if(opt.equals("√"))
                {
                    if(d1 > 0)
                        result.setText(""+Math.sqrt(d1));
                    else
                        result.setText("负数没有平方根");
                }
            }
            //CE  or  C
            if(t.equals(btn[6]) || t.equals(btn[7]))
            {
                result.setText("");
            }
            //←
            if(t.equals(btn[5]))
            {
                String s = result.getText();
                result.setText(s.substring(0,s.length()-1));
            }
            //±
            if(t.equals(btn[8]))
            {
                d1 = Double.parseDouble(result.getText());
                result.setText(""+(-d1));
            }
            //.
            if(t.equals(btn[26]))
            {
                if(result.getText().trim().indexOf(".") != -1) //判断字符串中是否已经包含了小数点
                {
                }
                else //如果没有小数点
                {
                    if(result.getText().trim().equals("0"))//如果开始为0
                    {
                        result.setText(("0"+e.getActionCommand()).toString());
                    }
                    else if(result.getText().trim().equals(""))//如果初时显示为空
                    {
                    }
                    else
                    {
                        result.setText((result.getText()+e.getActionCommand()).toString());
                    }
                }
            }
        }catch(Exception ee){} 

    }
}

运行结果:

ps:由于能力有限,第一行的按钮功能没有实现,关于菜单的地方还有一点不足之处。。。。。。哪位大神给我修改下?谢谢

仿windows的java计算器

时间: 2024-10-29 19:09:41

仿windows的java计算器的相关文章

【J2SE】java仿windows记事本

基于J2SE实现的一个记事本程序. 运行程序截图: 工程目录结构: 程序代码: package com.hblg; import java.awt.BorderLayout; import java.awt.FileDialog; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.aw

Android UI组件进阶(2)——仿Windows对话框

Android UI组件进阶(2)--仿Windows对话框 在开始本章前先祝大家中秋节快乐哈,相信很多上班的朋友都是放三天假的哈! 有时间的话回家陪陪父母吧!树欲静而风不止,子欲养而亲不待!岁月不饶人! 好了,道理和祝福语就说到这里了,今天给大家准备的是模仿Windows风格对话框! 效果图: 相信大部分的AlertDialog都是下面这个样子的: 今天给大家讲解的对话框是下面这样的: 对比两种对话框,站在用户的角度,相信你更加钟情于第二种颜色鲜明的对话框 好了下面就开始讲解如何制作模仿win

[C#]组合框设计windows加减乘除简单计算器应用

组合框使用方法,按照下面图片上提示,设计一个windows应用程序,实现不同运算. 界面设计: 代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace comb

java 计算器SWT/RAP(版本3)键盘鼠标兼容

java 计算器SWT/RAP(版本3)键盘鼠标兼容,之前版本也对,但存在线程失效问题,当多人访问时,就容易线程失效,一直犯得一个错误就是一直用static变量和static方法, 之前加了什么js界面控制什么的,都没用,去掉static就好了 package cn.lesaas.nof.rwtswt.ui.dialog; import java.math.BigDecimal; import org.eclipse.swt.SWT;import org.eclipse.swt.events.S

java设计之简单的JAVA计算器

做这个东西主要是为了练习一下以前学习过的java Swing,所以那些复杂的算法就没有加载到里面去........ 先展示一下效果....,额,当然不是这个样子....   ---> 代码: 1 package dialog_color; 2 3 import java.awt.BorderLayout; 4 import java.awt.Color; 5 import java.awt.Container; 6 import java.awt.FlowLayout; 7 import jav

java计算器 图形用户界面 升级版 v1.02

jsp页面: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.m

用Qt写的一个仿Windows记事本程序

闲得无聊加上自己喜欢Qt所以就写了这样一个仿windows记事本的程序,全部功能经测试可用.Qt版本5.5+win7x64 其中有部分逻辑比较乱,大家多多交流 备用链接:https://github.com/piaodonkey/notepad .pro部分: #------------------------------------------------- # # Project created by QtCreator 2015-09-12T21:33:50 # #------------

JAVA计算器算法实现

import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class BorderJFrame extends JFr

Windows下Java File对象创建文件夹时的一个"坑"

import java.io.File; import java.io.IOException; public class DirCreate { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String dirStr="D:"; File dir=new File(dirStr); System.out.println("====