import javaawt;import javaawtevent;import javaxswing;public class Calculator public static void mainString args new ShowCalculate; class ShowCalculate extends JFrame implements ActionListener priv
import java.awt.; import java.awt.event.; import javax.swing.*;
public class Calculator { public static void main(String[] args) { new ShowCalculate(); //创建ShowCalculate对象并显示计算器 } }
class ShowCalculate extends JFrame implements ActionListener{ //继承JFrame类并实现ActionListener接口 private JPanel jp; //面板对象 private TextField jf1; //文本框对象1 private TextField jf2; //文本框对象2 private TextField jf3; //文本框对象3 private JButton btnAdd; //加号按钮对象 private JButton btnMins; //减号按钮对象 private JButton btnCheng; //乘号按钮对象 private JButton btnChu; //除号按钮对象
ShowCalculate(){ //构造函数
this.setSize(300,400); //设置窗口大小
this.setTitle("计算器"); //设置窗口标题
this.setLocation(100, 100); //设置窗口位置
jp=new JPanel(); //实例化面板对象
this.setContentPane(jp); //将面板对象设置为窗口的内容面板
jf1=new TextField(); //实例化文本框对象1
jf2=new TextField(); //实例化文本框对象2
jf3=new TextField(); //实例化文本框对象3
btnAdd =new JButton("+"); //实例化加号按钮对象
btnAdd.addActionListener(this); //将加号按钮对象注册为监听器
btnMins=new JButton("-"); //实例化减号按钮对象
btnMins.addActionListener(this); //将减号按钮对象注册为监听器
btnCheng=new JButton("*"); //实例化乘号按钮对象
btnCheng.addActionListener(this); //将乘号按钮对象注册为监听器
btnChu=new JButton("/"); //实例化除号按钮对象
btnChu.addActionListener(this); //将除号按钮对象注册为监听器
jp.setLayout(new GridLayout(4,1)); //设置面板布局为4行1列的网格布局
jp.add(jf1); //将文本框对象1添加到面板中
jp.add(jf2); //将文本框对象2添加到面板中
JPanel jp1=new JPanel(); //实例化面板对象
jp1.setLayout(new GridLayout(1,4)); //设置面板布局为1行4列的网格布局
jp1.add(btnAdd); //将加号按钮对象添加到面板中
jp1.add(btnMins); //将减号按钮对象添加到面板中
jp1.add(btnCheng); //将乘号按钮对象添加到面板中
jp1.add(btnChu); //将除号按钮对象添加到面板中
jp.add(jp1); //将面板对象1添加到面板中
jp.add(jf3); //将文本框对象3添加到面板中
this.setVisible(true); //设置窗口可见
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //设置窗口关闭时退出程序
}
@Override
public void actionPerformed(ActionEvent e) { //实现ActionListener接口中的方法
int a1=0; //定义整型变量a1并初始化为0
int a2=0; //定义整型变量a2并初始化为0
a1=Integer.parseInt((String)jf1.getText()); //将文本框对象1中的内容转换为整型并赋值给a1
a2=Integer.parseInt((String)jf2.getText()); //将文本框对象2中的内容转换为整型并赋值给a2
if(e.getSource()==btnAdd){ //如果事件源是加号按钮
int a=a1+a2; //计算a1和a2的和并赋值给变量a
jf3.setText(""+a); //将a的值转换为字符串并显示在文本框对象3中
jf1.setText(""); //清空文本框对象1中的内容
jf2.setText(""); //清空文本框对象2中的内容
}
else if(e.getSource()==btnMins){ //如果事件源是减号按钮
jf3.setText(""+(a1-a2)); //计算a1和a2的差并显示在文本框对象3中
jf1.setText(""); //清空文本框对象1中的内容
jf2.setText(""); //清空文本框对象2中的内容
}
else if(e.getSource()==btnCheng){ //如果事件源是乘号按钮
jf3.setText(""+(a1*a2)); //计算a1和a2的积并显示在文本框对象3中
jf1.setText(""); //清空文本框对象1中的内容
jf2.setText(""); //清空文本框对象2中的内容
}
else if(e.getSource()==btnChu){ //如果事件源是除号按钮
jf3.setText(""+(a1/a2)); //计算a1和a2的商并显示在文本框对象3中
jf1.setText(""); //清空文本框对象1中的内容
jf2.setText(""); //清空文本框对象2中的内容
}
}
原文地址: https://www.cveoy.top/t/topic/fg5c 著作权归作者所有。请勿转载和采集!