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

转载于:https://www.cnblogs.com/UUUP/p/3808748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值