Home > Java > javaTutorial > How to implement a small calculator in Java GUI graphical interface development

How to implement a small calculator in Java GUI graphical interface development

WBOY
Release: 2023-05-01 23:49:18
forward
1612 people have browsed it

1. Design Goals

(1) Main functions: realize simple binocular operations such as addition, subtraction, multiplication, and division, and monocular operations such as square root and percentage

( 2) Accessibility function: Button "C" realizes clearing the text box; button "←" realizes backspace and deletes the rightmost character in the text box

2. Interface design

Create" Panel Object" and set its layout management mode to a GridLayout layout mode of 5 rows and 4 columns to accommodate 20 buttons. The text box and the panel that accommodates 20 button components use the border layout method to layout them to the form BorderLayout.NORTH and the central position BorderLayout.CENTER respectively;

Then set the text content of the 20 buttons: declare and create A String type array stores the text content on 20 buttons. Declare and create a JButton type (or Button type) array, and use a for loop to add text to the 20 buttons in sequence.

Let’s take a look at the final interface effect first:

How to implement a small calculator in Java GUI graphical interface development

3. Functional implementation

Using the "delegate event processing model" for event processing , in response to user operations. The main components used this time are buttons and text boxes, so they can be classified as ActionEvent classes. Use the ActionListener event listener interface to implement the actionPerformed method to respond to events.

Implementation of calculation function: Pay attention to the different processing of binary operators and unary operators. Binary operator defines a variable to store the value of the first operand and the value after the binary operation. The operation result is displayed in the text box by clicking "=". Unary operator, after entering the value, click the operator to display the operation result directly in the text box. The square root function is implemented by calling the sqrt() method of the Math class. The percentage operation can be directly multiplied by 0.01, because for example, 12%=12*0.01 0.12, a method to implement the calculation is specially defined for this purpose. Part of the code is as follows:

public void calculate(){
		char[]arr=input.getText().toCharArray();//将输入的计算表达式字符串存储在字符数组中便于查找运算符的位置
		int i=0;//移动标志变量
		while(&#39;0&#39;<=arr[i]&&arr[i]<=&#39;9&#39;||arr[i]==&#39;.&#39;)//去除数字与小数点以确定双目运算符的位置
		      i++;
		char operator=arr[i];//将该运算符存储起来
		//双目运算
		if(operator!=&#39;%&#39;&&operator!=&#39;√&#39;){
			String s=input.getText(),s1,s2;//s1,s2分别存储运算符前后的数值字符串
			s1=s.substring(0,i);
			s2=s.substring(i+1,s.length());
			Double left=Double.parseDouble(s1);//将运算符左边的数值字符串转换为浮点数
			Double right=Double.parseDouble(s2);//将运算符右边的数值字符串转换为浮点数
			//根据不同的运算符进行相应的计算
			if(operator==&#39;+&#39;)result=left+right;
			else if(operator==&#39;-&#39;)result=left-right;
			else if(operator==&#39;×&#39;)result=left*right;
			else if(operator==&#39;÷&#39;)result=left/right;
		}
		//单目运算
		else{
			String s=input.getText(),s1;
			s1=s.substring(0,s.length()-1);
			Double a=Double.parseDouble(s1);
			if(operator==&#39;%&#39;){
				result=0.01*a;
			}
			else if(operator==&#39;√&#39;){
				result=Math.sqrt(a);
			}
		}
	}
Copy after login

‏ Code idea: Take the operation expression 8 5 as an example. First get the calculation expression string "8 5" input by the user through the button component from the text box input, first convert it into a character array, if it is a binary operation, first find the position of the operator through a loop, and then use the StringTokenizer class The character segmentation and editing method substring(a,b) in the string obtains the string whose subscript starts from a and ends with b-1 (left-closed and right-open interval), and uses the operator as the dividing line to separate the two The numeric characters are separated, that is, the two characters '8' and '5' are obtained respectively, and then the Double.parseDouble() method is used to turn them into floating point numbers 8.0 and 5.0 that can be operated on. Finally, according to different operators Perform corresponding calculations and save the results in the variable result. The unary operator is the same, except that after splitting, there is only one left operand and no right operand.

Implementation of button "C" to clear the text box: call the member method setText("") of the text box object and reset it to an empty string

Button "←" exit Implementation of the grid: first get the string in the text box, then call the member method substring() to get the remaining substring after removing the last character, and finally set the string as the content of the text box object. Part of the code is as follows:

            String str=input.getText();
			if(str.length()>1){
				str=str.substring(0,str.length()-1);
				input.setText(str);
			}
			else{
				input.setText("");
			}
Copy after login

4. All codes

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.StringTokenizer;
public class Calculator extends JFrame implements ActionListener{
	JTextField input;//文本框,显示计算结果
	JButton []button=new JButton[20];//按钮数组,存放20个按钮组件
	JPanel pan=new JPanel();
	String name[]={"C","÷", "×", "←","7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "√", "%", "0", ".", "="};//按钮标签数组
	double result;//存储双目运算的结果
	public Calculator(){
		setTitle("模拟计算器—江海大");
		pan.setLayout(new GridLayout(5,4));//设置面板pan的布局格式为5行4列的网格布局,存放20个按钮
		input=new JTextField(20);
		input.setText("");
		input.setFont(new Font("宋体",Font.BOLD,18));
		input.setForeground(Color.BLUE);
		for(int i=0;i<button.length;i++){
			button[i]=new JButton(name[i]);
			button[i].setFont(new Font("黑体",Font.BOLD,20));
			button[i].addActionListener(this);//给每一个按钮注册事件监听器
			pan.add(button[i]);
		}
		add(input,BorderLayout.NORTH);
		add(pan,BorderLayout.CENTER);
		setSize(600,400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗体
	}
	//动作响应
	public void actionPerformed(ActionEvent e){
		//如果点击按钮 "C"则触发清空文本框的操作
		if(e.getSource()==button[0]){
			input.setText("");
		}
		//如果点击按钮"="则调用计算方法并在文本框显示结果
		else if(e.getSource()==button[19]){
			calculate();
			input.setText(""+result);//输出计算结果
		}
		//如果点击"<--"按钮则删去文本框内字符串的末尾字符
		else if(e.getSource()==button[3]){
			String str=input.getText();
			if(str.length()>1){
				str=str.substring(0,str.length()-1);
				input.setText(str);
			}
			else{
				input.setText("");
			}
		}
		//以字符串拼接的方式将点击的按钮的标签拼接起来,成为一个运算表达式字符串
		else{
			input.setText(input.getText()+e.getActionCommand());
		}
	}
	public void calculate(){
		char[]arr=input.getText().toCharArray();//将输入的计算表达式字符串存储在字符数组中便于查找运算符的位置
		int i=0;//移动标志变量
		while(&#39;0&#39;<=arr[i]&&arr[i]<=&#39;9&#39;||arr[i]==&#39;.&#39;)//去除数字与小数点以确定双目运算符的位置
		      i++;
		char operator=arr[i];//将该运算符存储起来
		//双目运算
		if(operator!=&#39;%&#39;&&operator!=&#39;√&#39;){
			String s=input.getText(),s1,s2;//s1,s2分别存储运算符前后的数值字符串
			s1=s.substring(0,i);
			s2=s.substring(i+1,s.length());
			Double left=Double.parseDouble(s1);//将运算符左边的数值字符串转换为浮点数
			Double right=Double.parseDouble(s2);//将运算符右边的数值字符串转换为浮点数
			//根据不同的运算符进行相应的计算
			if(operator==&#39;+&#39;)result=left+right;
			else if(operator==&#39;-&#39;)result=left-right;
			else if(operator==&#39;×&#39;)result=left*right;
			else if(operator==&#39;÷&#39;)result=left/right;
		}
		//单目运算
		else{
			String s=input.getText(),s1;
			s1=s.substring(0,s.length()-1);
			Double a=Double.parseDouble(s1);
			if(operator==&#39;%&#39;){
				result=0.01*a;
			}
			else if(operator==&#39;√&#39;){
				result=Math.sqrt(a);
			}
 
		}
	}
	public static void main(String[]args){
		new Calculator();
	}
}
Copy after login

5. Functional test

How to implement a small calculator in Java GUI graphical interface development

Addition

How to implement a small calculator in Java GUI graphical interface development

Subtraction

How to implement a small calculator in Java GUI graphical interface development

Multiplication

How to implement a small calculator in Java GUI graphical interface development

Division

How to implement a small calculator in Java GUI graphical interface development

Square root

How to implement a small calculator in Java GUI graphical interface development

Clear

How to implement a small calculator in Java GUI graphical interface development

The above is the detailed content of How to implement a small calculator in Java GUI graphical interface development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template