简易计算器+组合和内部
package com.zishi.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//简易计算器
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
public Calculator(){
//3个文本框
TextField num1 = new TextField(10); //columns:10字符数
TextField num2 = new TextField(10);
TextField num3 = new TextField(20); //最后结果框要大一点
//1个便签
Label label = new Label("+");
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(num1,num2,num3));
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取三个变量
private TextField num1,num2,num3;
public MyCalculatorListener(TextField num1,TextField num2,TextField num3){
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
组合:
package com.zishi.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//简易计算器
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public Calculator(){
//3个文本框
num1 = new TextField(10); //columns:10字符数
num2 = new TextField(10);
num3 = new TextField(20); //最后结果框要大一点
//1个便签
Label label = new Label("+");
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener(this));
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
}
//监听器类
class MyCalculatorListener implements ActionListener{
//获取三个变量
Calculator calculator = null;
public MyCalculatorListener(Calculator calculator){
this.calculator = calculator;
}
内部类
package com.zishi.lesson02;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//简易计算器
public class TestCalc {
public static void main(String[] args) {
new Calculator();
}
}
//计算器类
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public Calculator(){
//3个文本框
num1 = new TextField(10); //columns:10字符数
num2 = new TextField(10);
num3 = new TextField(20); //最后结果框要大一点
//1个便签
Label label = new Label("+");
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalculatorListener());
//布局
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
//监听器类
//内部类最大的好处就是可以畅通无阻的访问外部变量和方法
class MyCalculatorListener implements ActionListener{