[Java]基于JFrame的計算器界面及部分功能實現(xiàn)-創(chuàng)新互聯(lián)

完成效果預覽

成都創(chuàng)新互聯(lián)2013年至今,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務公司,擁有項目成都網(wǎng)站制作、網(wǎng)站建設(shè)網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元建水做網(wǎng)站,已為上家服務,為建水各地企業(yè)和個人服務,聯(lián)系電話:18980820575
程序設(shè)計 -布局設(shè)計-

整體布局采用BorderLayout,Center為程序主要交互部分,North為菜單界面。

主要界面由兩個采用GridLayout分布的子面板組成,兩個面板分別顯示計算過程和交互按鈕。

-主要使用控件-

JLabel:通過標簽顯示計算式與結(jié)果。

JButton:通過按鈕實現(xiàn)程序與用戶的基本交互。

JPanel:通過面板組建程序圖形界面的基本布局。

JMenubar/JMenu/JMenuItem:用于組建菜單。

Font:用于設(shè)置字體樣式。

-數(shù)據(jù)結(jié)構(gòu)-

通過數(shù)字棧與符號棧完成對算式的計算算法。

通過哈希表建立符號名稱到按鈕的映射。


代碼部分? 程序基本架構(gòu)

calculator.java
public class calculator {
    public static void main(String[] argv) {
        new app();
    }
}
app.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

public class app extends JFrame {

    private static String ex = "";
    private static JLabel expression, res;// 分別存儲表達式 計算結(jié)果
    private static Stacksign_stack = new Stack();// 符號棧
    private static Stacknumber_stack = new Stack();// 數(shù)字棧
    private static Double curIndex, totIndex;// 當前數(shù)字結(jié)果 整個表達式的數(shù)字結(jié)果
    private static final String buttonName[][] = { { "C", "÷", "×", "Back" }, { "7", "8", "9", "-" },
            { "4", "5", "6", "+" },
            { "1", "2", "3", "√" }, { "%", "0", ".", "=" } };
    private static JButton buttonList[][] = new JButton[5][4];
    private static HashMapbuttonMap = new HashMap();// 映射 符號->按鈕
    private static JMenuItem standardMode, sciMode, appearance, history;
    private static Double unit = 1.0;// 用來記錄小數(shù)最小單位

    // 計算結(jié)果并更新
    private static void calculate() {
        totIndex = 0.0;
        Stacksstack = (Stack) sign_stack.clone();
        Stacknstack = (Stack) number_stack.clone();
        if (sstack.empty() || sstack.firstElement() != '÷')
            nstack.push(curIndex);
        else {
            sstack.pop();
            sstack.push('×');
            nstack.push(1 / curIndex);
        }
        unit = 1.0;
        while (!sstack.empty()) {
            Character s = sstack.pop();
            if (s == '+') {
                double a = nstack.pop();
                totIndex += a;
            } else if (s == '-') {
                double a = nstack.pop();
                totIndex -= a;
            } else if (s == '×') {
                double a = nstack.pop(), b = nstack.pop();
                nstack.push(a * b);
            } else if (s == '÷') {
                double a = nstack.pop(), b = nstack.pop();
                nstack.push(b / a);
            }
        }
        totIndex += nstack.pop();
    }

    // 數(shù)字按鍵事件
    private static void NumberButtonAction(int n) {
        if (number_stack.size()< sign_stack.size()) {
            number_stack.push(curIndex);
            curIndex = 0.0;
        }
        if (unit.equals(1.0)) {
            curIndex = curIndex * 10 + n;
        } else {
            curIndex += n * unit;
            unit /= 10;
        }
        res.setText(tool.Rounding(Double.toString(curIndex)));
        ex += (char) (n + 48);
        expression.setText(ex);
    }

    // 符號按鍵事件
    private static void SignButtonAction(char sign) {
        calculate();
        res.setText(tool.Rounding(Double.toString(totIndex)));
        if (sign_stack.empty() || sign_stack.firstElement() != '÷')
            number_stack.push(curIndex);
        else {
            sign_stack.pop();
            sign_stack.push('×');
            number_stack.push(1 / curIndex);
        }
        unit = 1.0;
        curIndex = 0.0;
        sign_stack.push(sign);
        ex += sign;
        expression.setText(ex);
    }

    private static void buttonAction() {

        buttonMap.get("1").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(1);
            }

        });

        buttonMap.get("2").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(2);
            }

        });

        buttonMap.get("3").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(3);
            }

        });

        buttonMap.get("4").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(4);
            }

        });

        buttonMap.get("5").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(5);
            }

        });

        buttonMap.get("6").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(6);
            }

        });

        buttonMap.get("7").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(7);
            }

        });

        buttonMap.get("8").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(8);
            }

        });

        buttonMap.get("9").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(9);
            }

        });

        buttonMap.get("0").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NumberButtonAction(0);
            }

        });

        buttonMap.get("C").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ex = "";
                expression.setText(ex);
                curIndex = 0.0;
                unit = 1.0;
                res.setText(tool.Rounding(Double.toString(curIndex)));
                sign_stack.clear();
            }

        });

        buttonMap.get("=").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                calculate();
                number_stack.clear();
                sign_stack.clear();
                res.setText(tool.Rounding(Double.toString(totIndex)));
                number_stack.push(totIndex);
                curIndex = totIndex;
                ex = tool.Rounding(Double.toString(curIndex));
                expression.setText(ex);
            }

        });

        buttonMap.get("+").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                SignButtonAction('+');
            }

        });

        buttonMap.get("-").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                SignButtonAction('-');
            }

        });

        buttonMap.get("×").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                SignButtonAction('×');
            }

        });

        buttonMap.get("÷").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                SignButtonAction('÷');
            }

        });

        buttonMap.get("Back").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (ex.length() == 0) {
                    return;
                }
                char c = ex.charAt(ex.length() - 1);
                ex = ex.substring(0, ex.length() - 1);
                if (c == '.') {
                    unit = 1.0;
                } else if (!unit.equals(1.0)) {
                    unit *= 10;
                    curIndex -= (c - 48) * unit;
                } else {
                    if (c >= '0' && c<= '9') {
                        curIndex -= c - 48;
                        curIndex /= 10;
                    } else {
                        sign_stack.pop();
                        curIndex = number_stack.pop();
                        unit = tool.getDecimalUnit(curIndex);
                    }
                }
                expression.setText(ex);
                res.setText(tool.Rounding(Double.toString(curIndex)));
            }

        });

        buttonMap.get(".").addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (ex.charAt(ex.length() - 1) == '.')// 防止小數(shù)點重復輸入
                    return;
                ex += '.';
                expression.setText(ex);
                unit /= 10;
            }

        });

    }

    private void UI() {
        this.setLayout(new BorderLayout());

        // 設(shè)置字體格式
        Font font = new Font("黑體", Font.PLAIN, 50);
        Font buttonFont = new Font("黑體", Font.PLAIN, 25);
        Font menuFont = new Font("黑體", Font.PLAIN, 12);

        // 菜單
        JMenuBar bar = new JMenuBar();
        JMenu mode = new JMenu("模式");
        mode.setFont(menuFont);
        standardMode = new JMenuItem("標準");
        sciMode = new JMenuItem("科學");
        mode.add(standardMode);
        mode.add(sciMode);
        JMenu func = new JMenu("功能");
        func.setFont(menuFont);
        appearance = new JMenuItem("外觀設(shè)置");
        history = new JMenuItem("歷史記錄");
        func.add(appearance);
        func.add(history);
        bar.add(mode);
        bar.add(func);
        this.add("North", bar);

        //總面板
        JPanel panel = new JPanel(new GridLayout(2, 1));

        // 分面板一:計算器顯示界面
        JPanel show = new JPanel(new GridLayout(2, 1));
        expression = new JLabel();// 算術(shù)表達式
        expression.setFont(font);
        res = new JLabel(tool.Rounding(Double.toString(curIndex)));// 計算結(jié)果
        res.setFont(new Font("黑體", Font.PLAIN, 35));
        show.add(expression);
        show.add(res);

        // 分面板二:計算機按鍵
        JPanel buttonPanel = new JPanel(new GridLayout(5, 4));
        for (int i = 0; i< 5; i++) {
            for (int j = 0; j< 4; j++) {
                buttonList[i][j] = new JButton(buttonName[i][j]);
                buttonMap.put(buttonName[i][j], buttonList[i][j]);
                if (buttonName[i][j].equals("Back"))
                    buttonList[i][j].setFont(new Font("黑體", Font.PLAIN, 20));
                else
                    buttonList[i][j].setFont(buttonFont);
                if (buttonName[i][j].equals("="))
                    buttonList[i][j].setBackground(new Color(65, 105, 225));
                else if (i >= 1 && j<= 2)
                    buttonList[i][j].setBackground(Color.white);
                buttonPanel.add(buttonList[i][j]);
            }
        }

        panel.add(show);
        panel.add(buttonPanel);
        this.add(panel);

        //JFrame基本設(shè)置
        this.setVisible(true);
        this.setBounds(400, 150, 390, 550);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("燁的計算器");
    }

    app() {
        curIndex = 0.0;
        totIndex = 0.0;
        UI();
        buttonAction();
    }

}
tool.java
public abstract class tool {

    // 省略小數(shù)末尾的0
    public static String Rounding(String s) {
        if (s.lastIndexOf('.', s.length() - 1) == -1) {
            return s;
        }
        int i = s.length() - 1;
        for (; i >= 0; i--) {
            if (s.charAt(i) == '.')
                break;
            if (s.charAt(i) != '0') {
                return s.substring(0, i + 1);
            }
        }
        return s.substring(0, i);
    }

    // 獲取最小小數(shù)單位
    public static Double getDecimalUnit(Double n) {
        String s = Double.toString(n);
        if (s.indexOf('.') == -1) {
            return 1.0;
        }
        return Math.pow(0.1, s.length() - s.indexOf('.'));
    }
}

你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧

分享標題:[Java]基于JFrame的計算器界面及部分功能實現(xiàn)-創(chuàng)新互聯(lián)
當前URL:http://bm7419.com/article28/hcccp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、定制開發(fā)、移動網(wǎng)站建設(shè)網(wǎng)頁設(shè)計公司、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名