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);
              }
        }
        
        

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的计算器界面Java代码: ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CalculatorGUI extends JFrame implements ActionListener { private JPanel mainPanel; private JTextField inputField; private JButton button0; private JButton button1; private JButton button2; private JButton button3; private JButton button4; private JButton button5; private JButton button6; private JButton button7; private JButton button8; private JButton button9; private JButton buttonAdd; private JButton buttonSubtract; private JButton buttonMultiply; private JButton buttonDivide; private JButton buttonEquals; private JButton buttonClear; private double currentNumber; private String currentOperator; private boolean isNewNumber; public CalculatorGUI() { setTitle("Calculator"); setSize(300, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); mainPanel = new JPanel(new BorderLayout()); inputField = new JTextField(); inputField.setHorizontalAlignment(JTextField.RIGHT); inputField.setPreferredSize(new Dimension(300, 50)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); button0 = new JButton("0"); button1 = new JButton("1"); button2 = new JButton("2"); button3 = new JButton("3"); button4 = new JButton("4"); button5 = new JButton("5"); button6 = new JButton("6"); button7 = new JButton("7"); button8 = new JButton("8"); button9 = new JButton("9"); buttonAdd = new JButton("+"); buttonSubtract = new JButton("-"); buttonMultiply = new JButton("*"); buttonDivide = new JButton("/"); buttonEquals = new JButton("="); buttonClear = new JButton("C"); buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9); buttonPanel.add(buttonAdd); buttonPanel.add(button4); buttonPanel.add(button5); buttonPanel.add(button6); buttonPanel.add(buttonSubtract); buttonPanel.add(button1); buttonPanel.add(button2); buttonPanel.add(button3); buttonPanel.add(buttonMultiply); buttonPanel.add(buttonClear); buttonPanel.add(button0); buttonPanel.add(buttonEquals); buttonPanel.add(buttonDivide); button0.addActionListener(this); button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); button4.addActionListener(this); button5.addActionListener(this); button6.addActionListener(this); button7.addActionListener(this); button8.addActionListener(this); button9.addActionListener(this); buttonAdd.addActionListener(this); buttonSubtract.addActionListener(this); buttonMultiply.addActionListener(this); buttonDivide.addActionListener(this); buttonEquals.addActionListener(this); buttonClear.addActionListener(this); currentNumber = 0; currentOperator = ""; isNewNumber = true; mainPanel.add(inputField, BorderLayout.NORTH); mainPanel.add(buttonPanel, BorderLayout.CENTER); setContentPane(mainPanel); setVisible(true); } public void actionPerformed(ActionEvent e) { String buttonLabel = e.getActionCommand(); if (buttonLabel.equals("C")) { inputField.setText(""); currentNumber = 0; currentOperator = ""; isNewNumber = true; } else if (buttonLabel.equals("=")) { double result = 0; if (currentOperator.equals("+")) { result = currentNumber + Double.parseDouble(inputField.getText()); } else if (currentOperator.equals("-")) { result = currentNumber - Double.parseDouble(inputField.getText()); } else if (currentOperator.equals("*")) { result = currentNumber * Double.parseDouble(inputField.getText()); } else if (currentOperator.equals("/")) { result = currentNumber / Double.parseDouble(inputField.getText()); } inputField.setText(String.valueOf(result)); currentNumber = result; currentOperator = ""; isNewNumber = true; } else if (buttonLabel.equals("+")) { currentNumber = Double.parseDouble(inputField.getText()); currentOperator = "+"; isNewNumber = true; } else if (buttonLabel.equals("-")) { currentNumber = Double.parseDouble(inputField.getText()); currentOperator = "-"; isNewNumber = true; } else if (buttonLabel.equals("*")) { currentNumber = Double.parseDouble(inputField.getText()); currentOperator = "*"; isNewNumber = true; } else if (buttonLabel.equals("/")) { currentNumber = Double.parseDouble(inputField.getText()); currentOperator = "/"; isNewNumber = true; } else { if (isNewNumber) { inputField.setText(buttonLabel); isNewNumber = false; } else { inputField.setText(inputField.getText() + buttonLabel); } } } public static void main(String[] args) { new CalculatorGUI(); } } ``` 上述代码使用Java Swing GUI库创建了一个简单的计算器界面,并实现了基本的计算功能。用户可以通过按钮输入数字和运算符,计算器会在文本框中显示计算结果。界面还包括一个清除按钮,可以清除当前的计算结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值