首页 > 技术文章 > 使用Java制作简易计算器

yolo888666 2021-07-20 15:13 原文

import org.w3c.dom.Text;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//制作简易计算器
public class TestCalculator {
public static void main(String[] args) {
// 启动程序
new Calculator();
}
}
class Calculator{

public Calculator(){
//组合高于继承 能使用new包含进来的尽量用new,降低耦合度 Frame frame = new Frame()
// 也是一种重要的编程思想!
Frame frame = new Frame();
// 创建文本框并设置列长
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(20);
Label label = new Label("+");
Button button = new Button("=");
//流式布局
frame.setLayout(new FlowLayout());
frame.add(num1);
frame.add(label);
frame.add(num2);
frame.add(button);
frame.add(num3);
frame.pack();
frame.setVisible(true);
//使用匿名内部类监听窗口,用于关闭窗口
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//给按钮添加监听 用于触发事件,同时将文本框内容传参到MyActionListener类
button.addActionListener(new MyActionListener1(num1,num2, num3));

}

}
class MyActionListener1 implements ActionListener {

private TextField num1,num2,num3;

public MyActionListener1(TextField num1, TextField num2,TextField num3){
this.num1=num1;
this.num2=num2;
this.num3=num3;
}
// 点击按钮后计算结果
@Override
public void actionPerformed(ActionEvent actionEvent) {
// 获取加数和被加数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//计算结果显示于计算框
num3.setText(""+(n1+n2));
//将加数 被加数清空
num2.setText("");
num1.setText("");
}
}

效果图

 

 

 

推荐阅读