计算器案例
package com.zhang.Study.计算器案例; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Caculater { public static void main(String[] args) { new Mycaculter(); } } class Mycaculter extends Frame{ public Mycaculter(){ TextField num1 = new TextField(10);//创建文本框,设定最大字符数为10 TextField num2 = new TextField(10); TextField num3 = new TextField(10); //设置一个标签 Label label = new Label("+"); //设置一个按钮 Button button = new Button("="); //添加按钮监听事件 button.addActionListener(new MycaculterListener(num1,num2,num3)); //布局,采用流式布局,从左到右排列 setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); setVisible(true); } } class MycaculterListener implements ActionListener{ //获取三个变量 private TextField num1,num2,num3; //重载构造器,获取三个参数赋给三个值。 public MycaculterListener(TextField num1,TextField num2,TextField num3){ this.num1= num1; this.num2=num2; this.num3 = num3; } @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 int n1 = Integer.parseInt(num1.getText());//integer把String类转换成int类 int n2 = Integer.parseInt(num2.getText()); //2.将这个值进行加法运算后,放入第三个框 num3.setText(""+(n1+n2)); //清除前两个元素 num1.setText(""); num2.setText(""); } }