Write a simple calculator using Java AWT

1. Preface
This calculator is based on the AWT graphics library under the Java language. Although the function is simple, for beginners, it can lay the foundation for in-depth learning of Java in the future.
The calculator supports simple arithmetic operations.

2. Demonstration and effect
Main interface

3. Detailed explanation of each function implementation
(1) Interface setting and layout
Buttons are divided into two types, function type and input type button. Input type buttons are 0~9 number keys, others are function buttons.
The buttons are divided into 4*5 grids using the GridLayout layout manager. When adding buttons, you need to add them to the Panel type container from left to right and from top to bottom, and then use the GridLayout layout manager for the Panel type container.
The text box is placed at the top using the BorderLayout layout manager.

The menu bar contains operations and the other two parts. The
operations contain reset and exit, and the others contain author information.
The menu bar needs to be implemented with the MenuBar class, the elements in the menu bar need to be implemented with Menu, and the buttons in each element are implemented with MenuItem.
After creating the MenuItem, Menu and MenuBar objects, call the add() method of Menu to combine multiple MenuItems into a menu (you can also combine another Menu object to form a secondary menu), and then call the add() method of MenuBar to combine multiple MenuItems into a menu A menu is combined into a menu bar, and finally the setMenuBar() method of the Frame object is called to add a menu bar to the window.

The code is implemented as follows:

public class Calculator
{
    private Frame f = new Frame("计算器");
    private Frame info = new Frame("关于");
    private Button[] b = new Button[10];        //b为数字类型按钮
    private Button[] cal = new Button[8];       //cal为功能类型按钮    
    private TextField text = new TextField(30); //定义一个宽度为30的文本框

    //定义菜单栏
    private MenuBar mb = new MenuBar(); 
    private Menu option = new Menu("操作");     
    private Menu other = new Menu("其他");
    private MenuItem about = new MenuItem("关于");
    private MenuItem reset = new MenuItem("重置");
    private MenuItem exit = new MenuItem("退出");

    private Label information = new Label(); //用在“关于”窗口中

    //省略无关此部分代码

    public void init()
    {
        Panel p = new Panel();   //定义Panel类型容器p,用来盛装按钮

        for(int i = 0; i <= 9; i++)
            b[i] = new Button(""+i);  //将数字键依次从0开始命名
        //功能键命名
        cal[0] = new Button("+");
        cal[1] = new Button("-");
        cal[2] = new Button("*");
        cal[3] = new Button("/");
        cal[4] = new Button("=");
        cal[5] = new Button("退格");
        cal[6] = new Button(".");
        cal[7] = new Button("AC");
        //按顺序依次将按键添加到容器p中
        p.add(b[1]);p.add(b[2]);p.add(b[3]);p.add(cal[0]);
        p.add(b[4]);p.add(b[5]);p.add(b[6]);p.add(cal[1]);
        p.add(b[7]);p.add(b[8]);p.add(b[9]);p.add(cal[2]);
        p.add(cal[5]);p.add(b[0]);p.add(cal[6]);p.add(cal[3]);
        p.add(cal[7]);p.add(cal[4]);

        text.setEditable(false);               //将文本框设置为不可直接输入
        f.add(text,BorderLayout.NORTH);        //将文本框置于最顶端并添加至窗口f
        p.setLayout(new GridLayout(5,4,4,4));  //设置GridLayout布局管理器
        f.add(p);                              //将容器p添加到窗口f
        f.setMenuBar(mb);                      //设置菜单栏
        f.setSize(280,250)                     //将窗口大小设置为280*250像素
        //“关于”窗口
        info.setSize(250,100);
        info.add(information);
        information.setText("作者:APlus  CSDN博客:abc123lzf\n");
        info.setVisible(false);
        //省略无关此部分代码
    }
    //省略无关此部分代码
}

(2) Event listener
In order to enable each button to handle the user's operation, it is necessary to add an event handling mechanism to each component.

Three types of objects are mainly involved in event processing:
Event source: the place where the event occurs, usually each component, such as buttons, windows, menus, etc.
Events: Events encapsulate specific things that happen on GUI components. If the program needs to obtain relevant information about the events that occur on the GUI components, it needs to be obtained through the Event object.
Event Listener: Responsible for listening to events that occur in the event source and responding to various events.

Now back to the calculator:
for input keys (0~9 keys), we just need to enter a corresponding number in the text box after the user presses the key.
Code:

public class Calculator
{
    //省略无关此部分代码
    class NumListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == b[0])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"0");
                else
                {
                    text.setText("0");
                    flag2 = -1;
                }
            }
            //......直到b[9];
            else if(e.getSource() == b[9])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"9");
                else
                {
                    text.setText("9");
                    flag2 = -1;
                }
            }
        }       
    }
    public void init()
    {
        NumListener numListen = new NumListener();
        //将0~9按键添加一个事件监听器
        for(int i = 0; i <= 9; i++)
            b[i].addActionListener(numListen);
        //省略无关此部分代码
    }
}

For processing keys, we need to calculate the number entered after the user presses the key, so we need to create two string buffers. When the processing button is pressed for the first time, the text box information is copied to the first buffer and the text box is cleared. After the processing button is pressed for the second time, the text box information is copied to the second buffer. Convert the two buffers to double-type values ​​for calculation, and display the calculation result in the text box, then copy the calculation result to the first buffer and empty the second buffer for the next press processing button to prepare.
Code:

public class Calculator
{
    //定义两个缓冲区
    private String load1 = new String();
    private String load2 = new String();

    private int flag = 0;          //用来标记是否第一次按下功能按键
    private int flag2 = -1;        //flag2标记按下第一个功能按键后,按下第一个数字按键时将文本框清空
    private int Key = -1;          //用来标记上一个功能按键,-1表示没有按下功能按键

    class CalListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == cal[0])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 0;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) + Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                }
            }
            else if(e.getSource() == cal[1])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 1;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) - Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                }
            }
            else if(e.getSource() == cal[2])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 2;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) * Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                }
            }
            else if(e.getSource() == cal[3])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 3;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) /         Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                }
            }
            else if(e.getSource() == cal[4])
            {
                if(load1 != null && load2 == null)
                {
                    load2 = text.getText();
                    if(Key == 0)
                        text.setText(String.valueOf(Double.parseDouble(load1) + Double.parseDouble(load2)));
                    else if(Key == 1)
                        text.setText(String.valueOf(Double.parseDouble(load1) - Double.parseDouble(load2)));
                    else if(Key == 2)
                        text.setText(String.valueOf(Double.parseDouble(load1) * Double.parseDouble(load2)));
                    else if(Key == 3)
                        text.setText(String.valueOf(Double.parseDouble(load1) / Double.parseDouble(load2)));
                    Key = -1;
                    flag = 0;
                    flag2 = -1;
                    load1 = text.getText();
                    load2 = null;
                }
            }
        }
    }
    public void init()
    {
        CalListener calListen = new CalListener();
        load1 = load2 = null;

        cal[0].addActionListener(calListen);
        cal[1].addActionListener(calListen);
        cal[2].addActionListener(calListen);
        cal[3].addActionListener(calListen);
        cal[4].addActionListener(calListen);
        cal[5].addActionListener(e->               //退格按键
        {
            text.setText(text.getText().substring(0,text.getText().length()-1));
        });
        cal[6].addActionListener(e->               //小数点按键
        {
            text.setText(text.getText()+".");
        });
        cal[7].addActionListener(e->               //重置按键
        {
            load1 = load2 = null;
            Key = -1;
            flag2 = -1;
            flag = 0;
            text.setText("");
        });
    }
}

For AWT, a window listener is required to allow the user to close the window or end the program by clicking the "X" button in the upper right corner of the window. We can create a class to extend the WindowAdapter class and override the windowClosing() method to achieve this.
Code:

class WindowListener extends WindowAdapter
{
    public void windowClosing(WindowEvent e)
    {
        System.exit(0);
    }
}

For the menu bar keys, it is similar to the function key
code implementation:

public class Calculator
{
    public void init()
    {
        exit.addActionListener(e->System.exit(0));
        reset.addActionListener(e->
        {
            load1 = load2 = null;
            Key = -1;
            flag2 = -1;
            flag = 0;
            text.setText("");
        });

        about.addActionListener(e->
        {
            info.setVisible(true);
        });
    }
}

4. All codes

import java.awt.*;
import java.awt.event.*;

public class Calculator
{
    private Frame f = new Frame("计算器");
    private Frame info = new Frame("关于");

    private Button[] b = new Button[10];
    private Button[] cal = new Button[8];

    private MenuBar mb = new MenuBar();
    private Menu option = new Menu("操作");
    private Menu other = new Menu("其他");
    private MenuItem about = new MenuItem("关于");
    private MenuItem reset = new MenuItem("重置");
    private MenuItem exit = new MenuItem("退出");
    private Label information = new Label();

    private TextField text = new TextField(30);
    private int flag = 0;
    private int flag2 = -1;
    private int Key = -1;

    String load1 = new String();
    String load2 = new String();

    public void init()
    {
        Panel p = new Panel();
        NumListener numListen = new NumListener();
        CalListener calListen = new CalListener();

        load1 = load2 = null;

        for(int i = 0; i <= 9; i++)
            b[i] = new Button(""+i);

        info.setSize(250,100);
        information.setText("作者:APlus  CSDN博客:abc123lzf\n");

        for(int i = 0; i <= 9; i++)
            b[i].addActionListener(numListen);

        cal[0] = new Button("+");
        cal[1] = new Button("-");
        cal[2] = new Button("*");
        cal[3] = new Button("/");
        cal[4] = new Button("=");
        cal[5] = new Button("退格");
        cal[6] = new Button(".");
        cal[7] = new Button("AC");
        cal[0].addActionListener(calListen);
        cal[1].addActionListener(calListen);
        cal[2].addActionListener(calListen);
        cal[3].addActionListener(calListen);
        cal[4].addActionListener(calListen);
        cal[5].addActionListener(e->
        {
            text.setText(text.getText().substring(0,text.getText().length()-1));
        });
        cal[6].addActionListener(e->
        {
            text.setText(text.getText()+".");
        });
        p.add(b[1]);p.add(b[2]);p.add(b[3]);p.add(cal[0]);
        p.add(b[4]);p.add(b[5]);p.add(b[6]);p.add(cal[1]);
        p.add(b[7]);p.add(b[8]);p.add(b[9]);p.add(cal[2]);
        p.add(cal[5]);p.add(b[0]);p.add(cal[6]);p.add(cal[3]);
        p.add(cal[7]);p.add(cal[4]);

        text.setEditable(false);
        exit.addActionListener(e->System.exit(0));
        reset.addActionListener(e->
        {
            load1 = load2 = null;
            Key = -1;
            flag2 = -1;
            flag = 0;
            text.setText("");
        });
        cal[7].addActionListener(e->
        {
            load1 = load2 = null;
            Key = -1;
            flag2 = -1;
            flag = 0;
            text.setText("");
        });
        about.addActionListener(e->
        {
            info.setVisible(true);
        });

        option.add(reset);
        option.add(exit);
        other.add(about);
        mb.add(option);
        mb.add(other);
        f.setMenuBar(mb);


        f.add(text,BorderLayout.NORTH);
        p.setLayout(new GridLayout(5,4,4,4));

        info.add(information);
        info.addWindowListener(new WindowListener());
        f.addWindowListener(new WindowListener());
        f.add(p);
        f.setSize(280,250);
        f.setVisible(true);
    }

    class WindowListener extends WindowAdapter
    {
        public void windowClosing(WindowEvent e)
        {
            if(e.getSource() == f)
                System.exit(0);
            else if(e.getSource() == info)
                info.setVisible(false);
        }
    }

    class NumListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == b[0])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"0");
                else
                {
                    text.setText("0");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[1])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"1");
                else
                {
                    text.setText("1");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[2])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"2");
                else
                {
                    text.setText("2");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[3])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"3");
                else
                {
                    text.setText("3");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[4])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"4");
                else
                {
                    text.setText("4");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[5])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"5");
                else
                {
                    text.setText("5");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[6])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"6");
                else
                {
                    text.setText("6");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[7])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"7");
                else
                {
                    text.setText("7");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[8])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"8");
                else
                {
                    text.setText("8");
                    flag2 = -1;
                }
            }
            else if(e.getSource() == b[9])
            {
                if(flag2 == -1)
                    text.setText(text.getText()+"9");
                else
                {
                    text.setText("9");
                    flag2 = -1;
                }
            }
        }       
    }

    class CalListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getSource() == cal[0])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 0;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) + Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                    //flag = 0;
                }
            }
            else if(e.getSource() == cal[1])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 1;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) - Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                    //flag = 0;
                }
            }
            else if(e.getSource() == cal[2])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 2;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) * Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                    //flag = 0;
                }
            }
            else if(e.getSource() == cal[3])
            {
                if(flag == 0)
                {
                    load1 = text.getText();
                    flag = 1;
                    flag2 = Key = 3;
                }
                else if(flag == 1)
                {
                    load2 = text.getText();
                    text.setText(String.valueOf(Double.parseDouble(load1) / Double.parseDouble(load2)));
                    load1 = text.getText();
                    load2 = null;
                    //flag = 0;
                }
            }
            else if(e.getSource() == cal[4])
            {
                if(load1 != null && load2 == null)
                {
                    load2 = text.getText();
                    if(Key == 0)
                        text.setText(String.valueOf(Double.parseDouble(load1) + Double.parseDouble(load2)));
                    else if(Key == 1)
                        text.setText(String.valueOf(Double.parseDouble(load1) - Double.parseDouble(load2)));
                    else if(Key == 2)
                        text.setText(String.valueOf(Double.parseDouble(load1) * Double.parseDouble(load2)));
                    else if(Key == 3)
                        text.setText(String.valueOf(Double.parseDouble(load1) / Double.parseDouble(load2)));
                    Key = -1;
                    flag = 0;
                    flag2 = -1;
                    load1 = text.getText();
                    load2 = null;
                }
            }
        }
    }

    public static void main(String[] args)
    {
        new Calculator().init();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326126387&siteId=291194637