Java experiment: complete a simple calculator (window) that can complete addition, subtraction, multiplication, and division


foreword

I recently learned java form, using the swing library and awt library in java

Swing is a development toolkit for developing user interfaces of Java applications.

Based on the Abstract Window Toolkit (AWT) to enable cross-platform applications to use any pluggable look and feel. Swing developers can take advantage of Swing's rich, flexible features and modular components to create elegant user interfaces with very little code. All packages in the toolkit are named after swing, such as javax.swing, javax.swing.event.

AWT (Abstract Window Toolkit), translated into Chinese as Abstract Window Toolkit, provides a set of interfaces for interacting with the local graphical interface , and is a basic tool provided by Java for establishing and setting Java's graphical user interface . There is a one-to-one correspondence relationship between the graphics functions in AWT and the graphics functions provided by the operating system, which is called peers . When using AWT to write a graphical user interface , it is actually using the graphics library provided by the local operating system. Since the graphics libraries of different operating systems provide different styles and functions, functions that exist on one platform may not exist on another platform. In order to realize the concept of "write once, run anywhere" declared by the Java language, AWT has to realize platform independence by sacrificing functions, that is, the graphics functions provided by AWT are provided by various operating systems. The intersection of the provided graphics functions.


1. Experimental content

Complete a simple calculator that can add, subtract, multiply, and divide. As shown in Figure 1.


Figure 1 Simple Calculator Result Display

2. Experimental ideas

Create the desired form and various components (buttons), as well as various settings of the window (such as size, initial position, whether it can be dragged, etc., note that all settings must be in the setVisible(true) form before visualization

Initialize the form, and write out the listener class object (internal anonymous class), call the addXXXlistener method of the event source component object to register the listener to the event source (that is, the calculation method)

3. Experiment code

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

//两种创建顶层窗体的方法
//1、JFarame frame=new JFrame("我的窗口")
//2、定义一个类继承自JFrame
public class calculator extends JFrame {
    JLabel l_num1,l_op,l_num2,l_result;
    JTextField t_num1,t_op,t_num2,t_result;
    JButton b_cal,b_reset;
    public calculator(String title){
        super(title);//设置窗体标题
        setSize(300,350);//设置窗体大小
        setLocation(300,300);//设置窗体弹出的初始位置
        getContentPane();setBackground(new Color(100, 192, 43));
        setResizable(false);//不可改变大小
        init();
        setVisible(true);//设置窗体是否可见
    }
    public void init(){
        l_num1 = new JLabel("操作数1",JLabel.CENTER);
        l_op = new JLabel("操作符:",JLabel.CENTER);
        l_num2 = new JLabel("操作数2",JLabel.CENTER);
        l_result = new JLabel("计算结果:",JLabel.CENTER);
        t_num1 = new JTextField();
        t_op = new JTextField();
        t_num2 = new JTextField();
        t_result = new JTextField();
        b_cal = new JButton("计算");//事件源
        MyListener listener=new MyListener();//创建监听器类对象
        b_cal.addActionListener(listener);//调用事件源组件对象的addXXXlistener方法把监听器注册到事件源上
        b_reset = new JButton("重置");//事件源
        b_reset.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                reset();
            }
        });//匿名内部类,监听器三合一
        setLayout(new GridLayout(5,2));
        add(l_num1);add(t_num1);
        add(l_op);add(t_op);
        add(l_num2);add(t_num2);
        add(l_result);add(t_result);
        add(b_cal);add(b_reset);
    }
    //监听器的使用步骤
    //1、自定义一个类,让他实现XXXListener这个接口
    //2、创建事件监听器类对象(第一步中自定义的类)
    //3、调用事件源组件对象的addXXXlistener方法吧监听器注册到事件源上
    public class MyListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            // TODO Auto-generated method stud
            cal();
        }
        }
    //完成计算功能
    public void cal(){
        try{
            if(t_num1.getText().equals("")||t_op.getText().equals("")||t_num2.getText().equals("")){
                JOptionPane.showMessageDialog(null,"操作数或运算符不能为空","操作数或运算符为空",JOptionPane.WARNING_MESSAGE);
            }
            double num1 = Double.parseDouble(t_num1.getText());
            char op = t_op.getText().charAt(0);
            double num2 = Double.parseDouble(t_num2.getText());
            switch(op){
                case '+':t_result.setText(num1+num2+"");break;
                case '-':t_result.setText(num1-num2+"");break;
                case '*':t_result.setText(num1*num2+"");break;
                case '/':t_result.setText(num1/num2+"");break;
                default:JOptionPane.showMessageDialog(null,"非法的运算符");
        }
        } catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null,"操作数非法");
        }


    }
    //完成重置功能
    public void reset(){
        t_num1.setText("");
        t_op.setText("");
        t_num2.setText("");
        t_result.setText("");
    }

}

//测试类
public class TestCalculator {
    public static void main(String[] args){
        calculator ca = new calculator("计算器");

    }
}

4. Screenshot of Experimental Results

that's all


Summarize

This is all about the form of the calculator. I have to say that the form as a visualization is still very interesting and fulfilling.

Guess you like

Origin blog.csdn.net/m0_72471315/article/details/127871443