【中大中级实训】使用JavaSwing构造计算器

使用MyEclipse对组件进行拖拽,之后只用写ActionListener就好!

使用GridLayout网格管理器,也有一定的鲁棒性

效果图
效果图

效果图

效果图

效果图

效果图

/*
 * Calculator.java
 *
 * Created on 2018/4/4
 *
 * Creator : Peanut 16340291
 */


import java.awt.event.*;
import java.util.regex.*;

//represent the sign of the calculate
enum Sign {
    ADD, MINUS, MULTIPLE, DIVIDE, BLANK
}

public class Calculator extends javax.swing.JFrame {

    //To avoid magic number
    //Total-failure : my score get lower
    static private int nine = 9;
    static private int sixty = 60;

    //Element nowSign remains blank equals to user didn't select a sign.
    Sign nowSign = Sign.BLANK;

    //Fllowing two methods are used to see if the input is correct
    private boolean isDouble(String str) {  
        if (null == str || "".equals(str)) {  
            return false;  
        }  
        Pattern myPattern = Pattern.compile("^[-\\+]?[.\\d]*$");  
        return myPattern.matcher(str).matches();  
    }  
    // float or double

    public static boolean isNumber(String str) {
        for (int i = str.length(); --i >= 0;) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }  
    // Integer

    //ActionListener method for sign buttons
    public void signListener(ActionEvent event) {
        if (event.getSource() == add) {
            sign.setText("+");
            nowSign = Sign.ADD;
        } else if (event.getSource() == minus) {
            sign.setText("-");
            nowSign = Sign.MINUS;
        } else if (event.getSource() == multiple) {
            sign.setText("\u00d7");
            nowSign = Sign.MULTIPLE;
        } else if (event.getSource() == divide) {
            sign.setText("\u00f7");
            nowSign = Sign.DIVIDE;
        }
    }

    //check input data for ok button listener
    //Delivery complexity
    public int inputCheck(String str1,String str2){
        int state = 1;
        if(str1 == null || "".equals(str1)){
            history.append("\n"+"Input1 is blank ");
            state = 0;
        } 
        //If input field 1 doesn't have content.
        if(str2 == null || "".equals(str2)){
            history.append("\n"+"Input2 is blank ");
            state = 0;
        } 
        //If input field 2 doesn't have content.
        if ((!isDouble(str1) && !isNumber(str1) ) || (!isDouble(str2) && !isNumber(str2) )) {
            history.append("\n"+"Input contains non-number elements! ");
            state = 0;
        } 
        //If the inputs are incorrect
        if (nowSign == Sign.BLANK) {
            history.append("\n"+"Hadn't select a sign!");
            state = 0;
        }
        return state;
    }

    //ActionListener method for ok button 
    public void okListener(ActionEvent evt) {
        int state = 1; 
        //Flag,o represents error occured
        String str1, str2;
        str1 = input1.getText();
        str2 = input2.getText();
        state = inputCheck(str1,str2);
        if(state == 1){ 
            //Do the calculate
            float i1, i2;
            float RESULT = 0;
            i1 = Float.valueOf(str1);
            i2 = Float.valueOf(str2);
            if (nowSign == Sign.ADD) {
                RESULT= i1 + i2;
            }
            else if (nowSign == Sign.MINUS) {
                RESULT = i1 - i2;
            }
            if (nowSign == Sign.DIVIDE) {
                RESULT = i1 / i2;
            }
            if (nowSign == Sign.MULTIPLE) {
                RESULT = i1 * i2;
            }
            history.append("\n"+String.valueOf(RESULT));
            result.setText(String.valueOf(RESULT));
        } else { 
            //If error occured set the output field to 0 (still show the error imformation in result field)
            result.setText(String.valueOf(""));
        }
    }

    //Constructor
    public Calculator() {
        initComponents();
    }

    // GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        sign = new javax.swing.JLabel();        
        //Label to show sign
        input1 = new javax.swing.JTextField();      
        //Input field 1
        input2 = new javax.swing.JTextField();      
        //Input field 2
        equal = new javax.swing.JLabel();       
        //Label "="
        result = new javax.swing.JTextField();      
        //Text field to show current result
        add = new javax.swing.JButton();        
        minus = new javax.swing.JButton();
        multiple = new javax.swing.JButton();
        divide = new javax.swing.JButton();     
        //Sign buttons
        ok = new javax.swing.JButton();         
        //Press the button to show the result
        jScrollPane1 = new javax.swing.JScrollPane();   
        //Place "history" on this panel to scroll it
        history = new javax.swing.JTextArea();      
        //Text field to show history result

        //Set uneditable : only system can add text,users cannot change the content
        history.setEditable(false);
        result.setEditable(false);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        // Show text in central place
        sign.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        input1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        input2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        equal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        //Set text and action listener
        equal.setText("=");

        result.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        add.setText("+");
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signListener(evt);
            }
        });

        minus.setText("-");
        minus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signListener(evt);
            }
        });

        // Us '\' to avoid mess code
        multiple.setText("\u00d7");
        multiple.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signListener(evt);
            }
        });

        divide.setText("\u00f7");
        divide.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signListener(evt);
            }
        });

        ok.setText("OK");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okListener(evt);
            }
        });

        //Text field set
        history.setColumns(20);
        history.setRows(5);
        history.setText("History result:");

        //Set history on the panel to scroll it
        jScrollPane1.setViewportView(history);
        history.getAccessibleContext().setAccessibleParent(null);

        //Place swing components
        //Using group and grid layout
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING,
                                                false)
                                                .addComponent(
                                                        jScrollPane1,
                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        javax.swing.GroupLayout.Alignment.LEADING,
                                                        layout.createSequentialGroup()
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addComponent(
                                                                                        add,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                        sixty,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addComponent(
                                                                                        input1,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                        sixty,
                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addGap(nine,
                                                                                                        nine,
                                                                                                        nine)
                                                                                                .addComponent(
                                                                                                        sign,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addPreferredGap(
                                                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                .addComponent(
                                                                                                        minus,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addComponent(
                                                                                                        multiple,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                .addPreferredGap(
                                                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                .addComponent(
                                                                                                        divide,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                                                .addGroup(
                                                                                        layout.createSequentialGroup()
                                                                                                .addComponent(
                                                                                                        input2,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                                .addPreferredGap(
                                                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                                                .addComponent(
                                                                                                        equal,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                                        sixty,
                                                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(
                                                                        layout.createParallelGroup(
                                                                                javax.swing.GroupLayout.Alignment.LEADING,
                                                                                false)
                                                                                .addComponent(
                                                                                        result)
                                                                                .addComponent(
                                                                                        ok,
                                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                        sixty,
                                                                                        Short.MAX_VALUE))))
                                .addContainerGap(16, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addGroup(
                                                        layout.createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(
                                                                        result,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        sixty,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(
                                                                        input2,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        sixty,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(
                                                                        equal,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        sixty,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addComponent(
                                                        sign,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(
                                                        input1,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(
                                                        add,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(
                                                        ok,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(
                                                        minus,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(
                                                        multiple,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(
                                                        divide,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        sixty,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)));

        //No need for this project
        add.getAccessibleContext().setAccessibleName("add");
        minus.getAccessibleContext().setAccessibleName("minus");
        multiple.getAccessibleContext().setAccessibleName("multiple");
        divide.getAccessibleContext().setAccessibleName("divide");
        ok.getAccessibleContext().setAccessibleName("ok");

        pack();
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Calculator().setVisible(true);
            }
        });
    }

    //Swing components
    private javax.swing.JButton add;
    private javax.swing.JButton divide;
    private javax.swing.JLabel equal;
    private javax.swing.JTextField input1;
    private javax.swing.JTextField input2;
    private javax.swing.JButton minus;
    private javax.swing.JButton multiple;
    private javax.swing.JButton ok;
    private javax.swing.JTextField result;
    private javax.swing.JLabel sign;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea history;

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值