16键计算器-Java(CalculatorGUI)

import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
 * This class is to create a calculator GUI.
 * 
 * @author DuChenyang
 * @version 2022/6/1   1.2.0
 */

public class CalculatorGUI {
    
        private JTextField textField;
        private GridLayout gridLayout;
        private JButton buttons[][];
        private Panel buttonPanel;
        
        private String front = "", behind = "";
        private String result = null;
        private String opCode = null;
        private boolean pointFlag = false;
        private boolean opFlag = false;
        private boolean equalFlag = false;
        
        /**
         * The string array about buttons
         */
        String[][] names = { { "1", "2", "3", "+" }, { "4", "5", "6", "-" }, { "7", "8", "9", "×" }, { ".", "0", "=", "÷" } };
        
        private Color colorTitle = new Color(173, 216, 230);
        private Color colorContent = new Color(255 ,255, 240);
        private Color colorButton = new Color(0 ,206, 209);
        private Color colorText = new Color(255 ,248 ,220);
        private Dimension textFieldSize = new Dimension(0,60);
        private Dimension frameSize = new Dimension(400,300);

        public CalculatorGUI() {
            
            
            /**
             * define the layout type
             */
            gridLayout = new GridLayout(4,0);
            
            gridLayout.setHgap(5); //set the horizontal gap

            gridLayout.setVgap(5); //set the vertical gap
            
            
            /**
             * Create the button panel
             */
            buttonPanel = new Panel();
            buttonPanel.setLayout(gridLayout);
            
            /**
             * Component -----Button
             */
            buttons = new JButton[4][4];
            
            /**
             * Use nested loop to set value.
             */
            for (int row = 0; row < names.length; row++) {

                for (int col = 0; col < names.length; col++) {
                    
                    //Create the field of button
                    buttons[row][col] = new JButton(names[row][col]);
                    
                    //Set the color of the buttons
                    buttons[row][col].setBackground(colorButton);
                    
                    //Add the button to buttonPanel
                    buttonPanel.add(buttons[row][col]);
                    
                    if( row<3 && col<3 ) {
                        
                        buttons[row][col].addActionListener(new NumberListener());
                    }
                    
                    else if(col == 3) {
                        
                        buttons[row][col].addActionListener(new SignListener());
                    }
                                    
                    
                }
            }
            buttons[3][1].addActionListener(new NumberListener());
            buttons[3][0].addActionListener(new SignListener());
            buttons[3][2].addActionListener(new SignListener());
            
            /**
             * Component -----textField
             */
            textField = new JTextField();
            
            //Set the size of the textField
            
            textField.setPreferredSize(textFieldSize);
            //Set the color of the text fields
            textField.setBackground(colorText);    
            //Set the font of the text fields
            textField.setFont(new Font("宋体",Font.BOLD,20));  
        }    
        
        /**
         * a series of operators about frame.
         */
        public void launchFrame() {        
            
            
            /**
             * Create the frame and add the splitPane
             */
             JFrame frame = new JFrame("Calculator");
             
             /**
              * Add component to the frame
              */
             frame.getContentPane().add(textField, BorderLayout.NORTH);
             frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
             
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             //set the frame size
             frame.setSize(frameSize);
             
             /**
              * decorate the frame color of the window
              */
             frame.setUndecorated(true);
             frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);    
             
             /**
              * Create Self-defining theme
              */
             MetalLookAndFeel.setCurrentTheme(new MyDefaultMetalTheme());
             try {
                 
                 UIManager.setLookAndFeel(new MetalLookAndFeel());
              } catch (Exception e) {
                  e.printStackTrace();
              }
             
             /**
              * Set the self-defining theme to the frame. 
              */
              SwingUtilities.updateComponentTreeUI(frame);

              //Set the frame visible
              frame.setVisible(true);        
            
        }
        
        public static void main(String args[]) {
            
             CalculatorGUI  chatClient =  new CalculatorGUI();             
             chatClient.launchFrame();
            
            
        }
        
     
        
        class Calculator{
            
            private double frontNum = Double.valueOf(front);
            private double behindNum = Double.valueOf(behind);
            private double resultNum = 0;
            
            public void opAdd() {
                
                resultNum = frontNum + behindNum;                
                
        }
                        
            public void opSubtract() {
                
                resultNum = frontNum - behindNum;
            
        }    
            
            public void opMultiply() {
                
                resultNum = frontNum * behindNum;
                
        }
            
            public void opDivide() {                
                                    
                resultNum = frontNum / behindNum;    
       }
        
            
            public void opEqual() {    
                
                if(opCode.equals("+")) {
                    
                    opAdd();
                }
                
                else if (opCode.equals("-")) {
                    
                    opSubtract();
                }
                    
                else if (opCode.equals("×")) {
                    
                    opMultiply();
                }
                
                else {
                    
                    opDivide();
                    
                }    
                
                if(opCode.equals("÷") && behindNum == 0) {
                    
                    result = "Wrong in division!";
                }
                
                else {
                    
                    result = String.valueOf(resultNum);
                }    
                opCode = null;
                
                
       }        
            
 }        
        class NumberListener  implements ActionListener{

            @Override
            public void actionPerformed(ActionEvent e) {
                
                textField.setText(e.getActionCommand());
                
                
                if(opFlag == false) {
                    
                    if(equalFlag == true) {
                        
                        front = "";
                        behind = "";
                        equalFlag = false;
                    }
                    
                    if(pointFlag == false)
                        
                        front += e.getActionCommand();
                    
                    else {
                        
                        front = front +"." +e.getActionCommand();
                        
                        pointFlag = false;
                    }                        
                    
                    textField.setText("Front number : "+front);
                }
                
                else {
                    
                    if(equalFlag == true) {
                        
                        behind ="";
                        front = result;
                        equalFlag = false;
                    }
                    
                    if(pointFlag == false) {
                        
                        behind += e.getActionCommand();                        
                    }    
                    
                    else {
                        
                        behind = behind +"." +e.getActionCommand();    
                        pointFlag = false;
                        
                    }                    
                    
                    textField.setText("Behind number : "+behind);
                    opFlag = false;
                    
                    
                }            
                    
            }    
            
        }
        
        class SignListener implements ActionListener {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                
                if(e.getActionCommand() == ".") {
                    
                    pointFlag = true;
                    
                }    
                
                else if(e.getActionCommand() == "=") {
                    
                     Calculator calculator = new Calculator();
                     calculator.opEqual();
                     equalFlag = true;
                     
                     textField.setText("Result : " + result);                    
                    
                }
                
                else {
                    
                    opCode = e.getActionCommand();
                    opFlag = true;                    
                    
                }
                
            }
            
        }            
        
        /**
         * Create a Self-defining theme
         *
         * extend DefaultMetalTheme class
         *
         */
        class MyDefaultMetalTheme extends DefaultMetalTheme {    
            
             
            /**
             * These three methods is to set the color of the window title
             */
            public ColorUIResource getWindowTitleInactiveBackground() {
                return new ColorUIResource(colorTitle);
              }
            
            public ColorUIResource getWindowTitleBackground() {
                return new ColorUIResource(colorTitle);
              }

            public ColorUIResource getPrimaryControlHighlight() {
                return new ColorUIResource(colorTitle);
              }
            
            /**
             * This method is to set the color of the frame.
             */
            public ColorUIResource getPrimaryControlDarkShadow() {
                return new ColorUIResource(colorTitle);
              }
            /**
             * This method is to set the color of the control button.
             */
            public ColorUIResource getPrimaryControl() {
                return new ColorUIResource(colorTitle);
              }
             
            /**
             * These three methods is to set the color of the window Content.
             */
            public ColorUIResource getControlHighlight() {
                return new ColorUIResource(colorContent);
              }

            public ColorUIResource getControlDarkShadow() {
                return new ColorUIResource(colorContent);
              }

            public ColorUIResource getControl() {
                return new ColorUIResource(colorContent);
              }
        }
        
        

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值