【Java】利用Swing实现简单的计算器

Main.java

package myCalculator;
import javax.swing.JFrame;
public class Main {
    public static void main(String[] args) {
        MyFrame frame = new MyFrame();//创建窗口
        frame.setTitle("计算器");//设置窗口标题
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);//显示出来
        frame.setLocationRelativeTo(null);//将窗口显示在屏幕中间
    }
}

MyFrame.java

package myCalculator;
import javax.swing.JFrame;
public class MyFrame extends JFrame{
    public MyFrame() {
        add(new MyPanel());
        pack();
    }
}

MyPanel.java

package myCalculator;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class MyPanel extends JPanel{
    JTextField display;
    JPanel panel1;
    JPanel panel2;
    JPanel panel3;
    String nowButton;
    public MyPanel() {
        //整个窗体的布局
        BorderLayout borderLayout = new BorderLayout();
        setLayout(borderLayout);
        //面板1-北部
        panel1 = new JPanel();
        FlowLayout flowLayout = new FlowLayout();
        panel1.setLayout(flowLayout);
        display = new JTextField(20);
        display.setEnabled(false);//文本框能否输入
        panel1.add(display);
        add(panel1,BorderLayout.NORTH);
        
        //面板2-中部
        ActionListener command = new CommandAction();//command监听器
        //CommandAction是实现接口ActionListener的一个类
        panel2 = new JPanel();
        panel2.setLayout(new GridLayout(4,4));
        String [][]a = {{"7","8","9","+"},{"4","5","6","-"},{"1","2","3","*"},{".","0","=","/"}};
//        JButton buttons[][] = new JButton[4][4];
        for(int i=0;i<a.length;i++) {
            for(int j=0;j<a[i].length;j++) {
                addButton1(a[i][j],command);
            }
        }
        add(panel2,BorderLayout.CENTER);
        //面板3-南部
        panel3 = new JPanel();
        panel3.setLayout(new GridLayout(1,2));
        addButton2("BackSpace",command);
        addButton2("AC",command);
        add(panel3,BorderLayout.SOUTH);
    }
    //为面板2中的每个按钮注册监视器
    public void addButton1(String label, ActionListener listener) {
        JButton button = new JButton(label);//实例化每个按钮,并把字符串添加到按钮上
        button.addActionListener(listener);//给每个按钮注册监听器
        panel2.add(button);
    }
    //为面板3中的每个按钮注册监视器
    public void addButton2(String label, ActionListener listener) {
        JButton button = new JButton(label);
        button.addActionListener(listener);
        panel3.add(button);
    }
    
    class CommandAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            String nowButton = e.getActionCommand();
            if(nowButton != "BackSpace" && nowButton != "=" && nowButton != "AC") {
                display.setText(display.getText() + nowButton);
            }
            if(nowButton.equals("=")) {
                display.setText(calculate(display.getText()));
            }
            if(nowButton.equals("BackSpace")) {
                StringBuffer sb = new StringBuffer(display.getText());
                display.setText(sb.substring(0,sb.length()-1));
            }
            if(nowButton.equals("AC")) {
                display.setText("");
            }
        }
        public String calculate(String string) {
            StringBuffer sb = new StringBuffer(string);
            int commandCount = 0;// 操作符的数量
            int j = 0;//计数器
            
            for(j=0; j<sb.length(); j++) {
                if(sb.charAt(j)<='9' && sb.charAt(j)>='0' || sb.charAt(j)=='.') {
                    continue;
                    }
                else {
                    commandCount++;
                    }
                }
            //初始化字符数组和数字数组
                char[] command = new char[commandCount];
                String[] num = new String[commandCount+1];
                for(j=0;j<num.length;j++) {
                    num[j] = "";
                }
                
                int k=0;
                for(j=0; j<sb.length(); j++) {
                    if(sb.charAt(j)<='9' && sb.charAt(j)>='0' || sb.charAt(j)=='.') {
                        num[k] += sb.charAt(j);
                        continue;
                    }
                    else {
                        command[k] = sb.charAt(j);
                        k++;
                    }
                }
                
                double result = 0;
                for(int i=0; i<commandCount; i++) {
                    double num1 = Double.parseDouble(num[i]);
                    double num2 = Double.parseDouble(num[i+1]);
                    char cc = command[i];
                    
                    switch(cc) {
                    case '+':
                        result = num1+num2;
                        break;
                    case '-':
                        result = num1-num2;
                        break;
                    case '*':
                        result = num1*num2;
                        break;
                    case '/':
                        result = num1/num2;
                        break;
                    default:
                        break;    
                    }
                    num[i+1] = String.valueOf(result);
                }
                return String.valueOf(result);
        }
    }
}

效果:

 

本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/15374270.html

posted @ 2021-10-06 21:21  木子欢儿  阅读(55)  评论(0编辑  收藏  举报