简单计算器实现含源码。

1.界面如下,有点丑,勿怪。

2.整体代码

 
 
package com.kenick.layout;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

public class SimpleCalculator {
	private TextField textField; //输入及计算结果显示框
	private int firstNum; // 记录第一次输入值
	private final List<String> fh = new ArrayList<String>(); // 记录输入的运算符合
	
	public SimpleCalculator() {
		// 初始化面板
		initPanel();
	}
	
	private void initPanel() {
		Frame frame = new Frame("计算器 ");
		// 面板最最左边处于屏幕中间,整体感觉会偏右下
		frame.setLocationRelativeTo(null);
		
		// 在北部面板中添加文本框
		Panel northPanel = new Panel();
		textField = new TextField(30);
		northPanel.add(textField);
		frame.add(northPanel,BorderLayout.NORTH);
		
		// 在南方面板中添加数字按键和按钮事件
		Panel southPanel =  new Panel();
		GridLayout gridLayout = new GridLayout(3, 5, 4, 4);
		southPanel.setLayout(gridLayout);
		String[] fuhao = new String[]{"0","1","2","3","4","5","6","7","8","9","+","-","*","/","="};
		for(int i=0;i<fuhao.length;i++){
			final Button tmpButton = new Button(fuhao[i]);
			tmpButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					String text = textField.getText();
					String buttonLable = tmpButton.getLabel();
					if(buttonLable.contains("+")||buttonLable.contains("-")|| buttonLable.contains("*")||buttonLable.contains("/")){
						fh.add(buttonLable);
						firstNum = Integer.valueOf(text);
						textField.setText("");
					}else if(buttonLable.contains("=")){
						int secondNum = Integer.valueOf(text);
						int result = -1;
						if(fh.size()==1){
							String fhStr = fh.get(0);
							switch (fhStr) {
							case "+":
								result = firstNum+secondNum;
								break;
							case "-":
								result = firstNum-secondNum;
								break;
							case "*":
								result = firstNum*secondNum;
								break;
							case "/":
								result = firstNum/secondNum;
								break;
							default:
								break;
							}
							textField.setText(result+"");
							fh.clear();
						}
					}else{
						textField.setText(text+buttonLable);
					}
				}
			});
			southPanel.add(tmpButton);
		}
		
		frame.add(southPanel);
		frame.pack(); // 窗体大小自适应
		frame.setVisible(true); // 窗体可见
		
		// 窗口关闭事件
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	// 运行main方法即可
	public static void main(String[] args) {
		new SimpleCalculator();
	}
}




猜你喜欢

转载自blog.csdn.net/leadseczgw01/article/details/76718393
今日推荐