Java Swing写简单计算器以及拓展贷款计算器(等额本息和等额本金计算可以单独拿出来用)

这篇博客介绍了如何使用Java Swing构建一个简单的计算器,并详细讲解了如何实现等额本息和等额本金两种贷款计算方式,代码部分来源于CSDN上的相关文章链接。

1. 简单计算器

纯手写

package com.jisuanqi;



import com.sun.xml.internal.ws.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

/**
 * @date 2020/12/7 - 9:33
 */
public class MyCalculator {

    private JFrame myCalculator;//计算器主页面
    private JTextField display;//文本框
    private JTextField result;//得到结果
    private JPanel jPanel1;
    private String nowButton;//输入的按钮
    private JPanel jP_button;//按钮布局
    private String str="";//输入的内容

    private JFrame expansion;
    private String x;//切换按钮
    private String y;//返回按钮
    private JPanel jPanel2;
    private JPanel jGroup1;
    private JPanel jGroup2;
    private JPanel jGroup3;
    private JPanel jGroup4;
    private JPanel jGroup5;
    private JPanel jGroup6;
    private JPanel jGroup7;
    private JPanel jGroup8;//按钮
    private String rb;//单选按钮
    private JRadioButton rButton1;
    //private String rb2;//单选按钮
    private JRadioButton rButton2;
    ButtonGroup group ;
    private JLabel jLabel1;//还款方式
    private JLabel jLabel2;//贷款年限
    private JLabel jLabel3;//贷款金额
    private JLabel jLabel4;//贷款年利率
    private JLabel jLabel5;//月均还款
    private JLabel jLabel6;//利息总额
    private JLabel jLabel7;//还款总额

    private JTextField jTextField2;
    private JTextField jTextField3;
    private JTextField jTextField4;
    private JTextField jTextField5;
    private JTextField jTextField6;
    private JTextField jTextField7;

    private String jb1;//计算
    private String jb2;//重新计算

    private DecimalFormat df = new DecimalFormat("0.000");

    public MyCalculator(){
        myCalculator=new JFrame("简易计算器");
        myCalculator.setVisible(true);
        myCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        result = new JTextField(50);
        result.setBackground(Color.PINK);
        result.setFont(new Font("楷体",Font.BOLD,30));
        result.setEnabled(true);
        display=new JTextField(50);
        display.setBackground(Color.LIGHT_GRAY);
        display.setFont(new Font("楷体",Font.BOLD,20));
        display.setEnabled(true);
        jPanel1= new JPanel(new BorderLayout(0,0));
        jPanel1.add(display,BorderLayout.CENTER);
        jPanel1.add(result,BorderLayout.SOUTH);
        myCalculator.add(jPanel1,BorderLayout.NORTH);


        jP_button=new JPanel();
        jP_button.setLayout(new GridLayout(5,4));
        ActionListener command = new CommandListener();
        ActionListener command1 = new expansionListener();
        addButton("1",command);
        addButton("2",command);
        addButton("3",command);
        addButton("+",command);
        addButton("4",command);
        addButton("5",command);
        addButton("6",command);
        addButton("-",command);
        addButton("7",command);
        addButton("8",command);
        addButton("9",command);
        addButton("*",command);
        addButton(".",command);
        addButton("0",command);
        addButton("sqrt",command);
        addButton("/",command);
        addButton("=",command);
        addButton("back",command);
        addButton("AC",command);
        addButton1("高级",command1);

        myCalculator.add(jP_button,BorderLayout.CENTER);
        myCalculator.setBounds(300,300,500,500);

/*====================================================================*/
        expansion = new JFrame("贷款计算器");
        expansion.setVisible(false);
        expansion.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ActionListener command2 = new backListener();
        jPanel2=new JPanel(new GridLayout(1,3));
        JTextField test = new JTextField(30);
        test.setText("这里是测试");
        jPanel2.add(test);
        addButton2("返回",command2);

        jLabel1 = new JLabel("还款方式:      ");
        jLabel2 = new JLabel("贷款年限(年):  ");
        jLabel3 = new JLabel("贷款金额(万元):");
        jLabel4 = new JLabel("贷款利率(%):   ");
        jLabel5 = new JLabel("月均还款(元):  ");
        jLabel6 = new JLabel("利息总额(元):  ");
        jLabel7 = new JLabel("还款总额(元):  ");
        jLabel1.setFont(new Font("楷体", Font.BOLD,20));
        jLabel2.setFont(new Font("楷体", Font.BOLD,20));
        jLabel3.setFont(new Font("楷体", Font.BOLD,20));
        jLabel4.setFont(new Font("楷体", Font.BOLD,20));
        jLabel5.setFont(new Font("楷体", Font.BOLD,20));
        jLabel6.setFont(new Font("楷体", Font.BOLD,20));
        jLabel7.setFont(new Font("楷体", Font.BOLD,20));



        ActionListener rbCommand = new selectListener();
        group = new ButtonGroup();

        jGroup1 = new JPanel();
        jGroup1.add(jLabel1);
        addRButton1("等额本息",rbCommand);
        addRButton2("等额本金",rbCommand);

        jGroup2 = new JPanel();

        jGroup3 = new JPanel();
        jGroup4 = new JPanel();
        jGroup5 = new JPanel();
        jGroup6 = new JPanel();
        jGroup7 = new JPanel();
        jGroup8 = new JPanel();

        jTextField2= new JTextField(10);
        jTextField3= new JTextField(10);
        jTextField4= new JTextField(10);
        jTextField5= new JTextField(10);
        jTextField6= new JTextField(10);
        jTextField7= new JTextField(10);

        jGroup2.add(jLabel2);
        jGroup3.add(jLabel3);
        jGroup4.add(jLabel4);
        jGroup5.add(jLabel5);
        jGroup6.add(jLabel6);
        jGroup7.add(jLabel7);

        jGroup2.add(jTextField2);
        jGroup3.add(jTextField3);
        jGroup4.add(jTextField4);
        jGroup5.add(jTextField5);
        jGroup6.add(jTextField6);
        jGroup7.add(jTextField7);

        /* */
        ActionListener resultCommand1=new moneyListener1();
        ActionListener resultCommand2=new moneyListener2();
        resultButton("计算",resultCommand1);
        resultButton("重新计算",resultCommand2);



        expansion.setLayout(new GridLayout(9,0,0,0));
        expansion.add(jGroup1);
        expansion.add(jGroup2);
        expansion.add(jGroup3);
        expansion.add(jGroup4);
        expansion.add(jGroup8);
        expansion.add(jGroup5);
        expansion.add(jGroup6);
        expansion.add(jGroup7);


        expansion.add(jPanel2,BorderLayout.SOUTH);
        //expansion.add(jGroup1,BorderLayout.NORTH);

        expansion.setBounds(300,300,500,500);


    }
    /*JRadioButton按钮*/
    public  void addRButton1(String str,ActionListener listener){
        rButton1=new JRadioButton(str);
        rButton1.addActionListener(listener);
        rButton1.setFont(new Font("楷体", Font.BOLD,20));
        group.add(rButton1);
        jGroup1.add(rButton1);
    }
public  void addRButton2(String str,ActionListener listener){
        rButton2=new JRadioButton(str);
        rButton2.addActionListener(listener);
        rButton2.setFont(new Font("楷体", Font.BOLD,20));
        group.add(rButton2);
        jGroup1.add(rButton2);
    }

    /*返回普通计算机页面*/
    public void addButton2(String label2,ActionListener listener2){
        JButton button = new JButton(label2);
        button.addActionListener(listener2);
        jPanel2.add(button);
    }
    /*跳转高级页面按钮*/
    public void addButton1(String label1,ActionListener listener1){
        JButton button = new JButton(label1);
        button.addActionListener(listener1);
        jP_button.add(button);
    }
    /*普通计算机按钮*/
    public void addButton(String label,ActionListener listener){
        JButton button= new JButton(label);
        button.addActionListener(listener);
        jP_button.add(button);
    }

    public void resultButton(String label,ActionListener listener){
        JButton button= new JButton(label);
        button.addActionListener(listener);
        jGroup8.add(button);
    }


    class CommandListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            nowButton=e.getActionCommand();
            if(nowButton.equals("=")){
                str=getResult(str);
                result.setText(str);

            }else if(nowButton.equals("+")||nowButton.equals("-")||nowButton.equals("*")||
                    nowButton.equals("/")||nowButton.equals("sqrt")||nowButton.equals("^")){
                display.setText(display.getText()+nowButton);
                str=str+" "+nowButton+" ";
            }else if(nowButton.equals("AC")){
                display.setText("");
                result.setText("");
                str="";

            }else if(nowButton.equals("back")){
                str=str.substring(0,str.length()-1);
                display.setText(str);
            }else {

                    str=str+nowButton;
                    display.setText(str);
            }


        }
    }
    public String getResult(String str1){
        Double result = 0.0;
        String []all=str1.split(" ");
        for(int i=0;i<all.length;i++){
            switch (all[i]){
                case "+":
                    result=result+(Double.parseDouble(all[i-1])+Double.parseDouble(all[i+1]));
                    break;
                case "-":
                    result=result+(Double.parseDouble(all[i-1])-Double.parseDouble(all[i+1]));
                    break;
                case "*":
                    result=result+(Double.parseDouble(all[i-1])*Double.parseDouble(all[i+1]));
                    break;
                case "/":
                    result=result+(Double.parseDouble(all[i-1])/Double.parseDouble(all[i+1]));
                    break;
                case "sqrt":
                    result=result+(Math.sqrt(Double.parseDouble(all[i-1])));
                    break;
                case "^":
                    result=result+Math.pow(Double.parseDouble(all[i-1]),Double.parseDouble(all[i+1]));
            }
        }
        return result+"";
    }
/*=================================*/
    class expansionListener extends CommandListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            x=e.getActionCommand();
            myCalculator.setVisible(false);
            expansion.setVisible(true);
        }
    }
    class backListener extends CommandListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            y=e.getActionCommand();
            myCalculator.setVisible(true);
            expansion.setVisible(false);
        }
    }
    //rb监听
    class selectListener extends CommandListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            rb=e.getActionCommand();

        }
    }

    class moneyListener1 extends CommandListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            jb1 = e.getActionCommand();

            Double str2 = Double.parseDouble(jTextField2.getText());//贷款年份
            Double str3 = Double.parseDouble(jTextField3.getText()) * 10000;//贷款金额
            Double str4 = Double.parseDouble(jTextField4.getText()) / 100;//年利率
            Double monthRate = str4 / 12;
            double month =  12 * str2;
            Double result1 = 0.0;//月均还款
            Double result2 = 0.0;//利息总额
            Double result3 = 0.0;//还款总额
            if (rButton1.isSelected()) {
                DK dk = new DK(str3, (int) month,str4);
                result3=dk.getASum((int) month)+dk.getBSum((int) month);
                result2=result3-str3;
                result1=result3/month;
                jTextField5.setText(df.format(result1));
                jTextField6.setText(df.format(result2));
                jTextField7.setText(df.format(result3));
            }
            if (rButton2.isSelected()) {
                result2=AverageCapitalUtils.getInterestCount(str3,str4, (int) month);
                result3=result2+str3;
                result1=result3/month;
                jTextField5.setText(df.format(result1));
                jTextField6.setText(df.format(result2));
                jTextField7.setText(df.format(result3));
            }

        }
    }
        class moneyListener2 extends CommandListener{
            @Override
            public void actionPerformed(ActionEvent e) {
                group.clearSelection();
                jb2=e.getActionCommand();
                jTextField2.setText("");
                jTextField3.setText("");
                jTextField4.setText("");
                jTextField5.setText("");
                jTextField6.setText("");
                jTextField7.setText("");
            }
        }




    public static void main(String[] args) {
        new MyCalculator();
    }

}

2. 等额本息和等额本金

这两个都是抄的
https://blog.csdn.net/qq_43639296/article/details/84307800?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4.not_use_machine_learn_pai&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4.not_use_machine_learn_pai

https://blog.csdn.net/xuejianbest/article/details/100150963?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160791135519725211939503%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=160791135519725211939503&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-3-100150963.first_rank_v2_pc_rank_v29&utm_term=java%E7%AD%89%E9%A2%9D%E6%9C%AC%E6%81%AF&spm=1018.2118.3001.4449

package com.jisuanqi;

/**
 * @date 2020/12/14 - 10:05
 */
/**
 * 等额本息还款金额计算类
 */
public class DK {
    private double A; // 贷款总额
    private double P; // 年利率
    private double p; // 月利率
    private int m; // 贷款期限(月)

    private double a1; // 第1个月所还本金
    private double b1; // 第1个月所还利息
    private double x; // 每月所还金额

    /**
     * @param A
     *          贷款总额
     * @param m
     *          贷款期限(月)
     * @param P
     *          年利率
     */
    public DK(double A, int m, double P) {
        this.A = A;
        this.m = m;
        this.P = P;
        this.p = this.P / 12;

        this.b1 = A * p;
        this.a1 = A * p / (Math.pow(1 + p, m) - 1);
        this.x = a1 + b1;
    }

    /*public static void main(String[] args) {
        double A = 50 * 10000.0;
        double P = 0.05;
        int m = 360;

        DK dk = new DK(120000, 120, 0.0486);
        System.out.println(String.format("%.2f", dk.getX()));
        double res=0.0;
        res=dk.getASum(120)+dk.getBSum(120);
        System.out.println(res);
        System.out.println(dk.getASum(120));
        System.out.println(dk.getBSum(120));
    }*/

    /**
     * @return 每月所还金额
     */
    public double getX() {
        return this.x;
    }

    /**
     * @param i
     *          月份
     * @return 返回第i个月所还本金
     */
    public double getAi(int i) {
        return this.a1 * Math.pow(1 + p, i - 1);
    }

    /**
     * @param i
     *          月份
     * @return 返回第i个月所还利息
     */
    public double getBi(int i) {
        return this.x - getAi(i);
    }

    /**
     * @param i
     *          月份
     * @return 返回到第i月所还本金总和
     */
    public double getASum(int i) {
        double sum = 0.0;
        for (int j = 1; j <= i; j++) {
            sum += getAi(j);
        }
        return sum;
    }

    /**
     * @param i
     *          月份
     * @return 返回到第i月所还利息总和
     */
    public double getBSum(int i) {
        double sum = 0.0;
        for (int j = 1; j <= i; j++) {
            sum += getBi(j);
        }
        return sum;
    }
}


package com.jisuanqi;//等额本金
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 等额本金是指一种贷款的还款方式,是在还款期内把贷款数总额等分,每月偿还同等数额的本金和剩余贷款在该月所产生的利息,这样由于每月的还款本金额固定,
 * 而利息越来越少,借款人起初还款压力较大,但是随时间的推移每月还款数也越来越少。
 */
public class AverageCapitalUtils {

    /**
     * 等额本金计算获取还款方式为等额本金的每月偿还本金和利息
     * <p>
     * 公式:每月偿还本金=(贷款本金÷还款月数)+(贷款本金-已归还本金累计额)×月利率
     *
     * @param invest     总借款额(贷款本金)
     * @param yearRate   年利率
     * @param totalMonth 还款总月数
     * @return 每月偿还本金和利息, 不四舍五入,直接截取小数点最后两位
     */
    public static Map<Integer, Double> getPerMonthPrincipalInterest(double invest, double yearRate, int totalMonth) {
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        // 每月本金
        double monthPri = getPerMonthPrincipal(invest, totalMonth);
        // 获取月利率
        double monthRate = yearRate / 12;
        monthRate = new BigDecimal(monthRate).setScale(6, BigDecimal.ROUND_DOWN).doubleValue();
        for (int i = 1; i <= totalMonth; i++) {
            double monthRes = monthPri + (invest - monthPri * (i - 1)) * monthRate;
            monthRes = new BigDecimal(monthRes).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
            map.put(i, monthRes);
        }
        return map;
    }

    /**
     * 等额本金计算获取还款方式为等额本金的每月偿还利息
     * <p>
     * 公式:每月应还利息=剩余本金×月利率=(贷款本金-已归还本金累计额)×月利率
     *
     * @param invest     总借款额(贷款本金)
     * @param yearRate   年利率
     * @param totalMonth 还款总月数
     * @return 每月偿还利息
     */
    public static Map<Integer, Double> getPerMonthInterest(double invest, double yearRate, int totalMonth) {
        Map<Integer, Double> inMap = new HashMap<Integer, Double>();
        double principal = getPerMonthPrincipal(invest, totalMonth);
        Map<Integer, Double> map = getPerMonthPrincipalInterest(invest, yearRate, totalMonth);
        for (Map.Entry<Integer, Double> entry : map.entrySet()) {
            BigDecimal principalBigDecimal = new BigDecimal(principal);
            BigDecimal principalInterestBigDecimal = new BigDecimal(entry.getValue());
            BigDecimal interestBigDecimal = principalInterestBigDecimal.subtract(principalBigDecimal);
            interestBigDecimal = interestBigDecimal.setScale(2, BigDecimal.ROUND_DOWN);
            inMap.put(entry.getKey(), interestBigDecimal.doubleValue());
        }
        return inMap;
    }

    /**
     * 等额本金计算获取还款方式为等额本金的每月偿还本金
     * <p>
     * 公式:每月应还本金=贷款本金÷还款月数
     *
     * @param invest     总借款额(贷款本金)
     * @param totalMonth 还款总月数
     * @return 每月偿还本金
     */
    public static double getPerMonthPrincipal(double invest, int totalMonth) {
        BigDecimal monthIncome = new BigDecimal(invest).divide(new BigDecimal(totalMonth), 2, BigDecimal.ROUND_DOWN);
        return monthIncome.doubleValue();
    }

    /**
     * 等额本金计算获取还款方式为等额本金的总利息
     *
     * @param invest     总借款额(贷款本金)
     * @param yearRate   年利率
     * @param totalMonth 还款总月数
     * @return 总利息
     */
    public static double getInterestCount(double invest, double yearRate, int totalMonth) {
        BigDecimal count = new BigDecimal(0);
        Map<Integer, Double> mapInterest = getPerMonthInterest(invest, yearRate, totalMonth);

        for (Map.Entry<Integer, Double> entry : mapInterest.entrySet()) {
            count = count.add(new BigDecimal(entry.getValue()));
        }
        return count.doubleValue();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值