回顾Java组合内部类
简易计算器简化代码,组合
面向对象的写法
对象.
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 TextCalc { public static void main(String[] args) { new Calculator().loadFrame(); } } //计算器类 class Calculator extends Frame{ //属性 TextField num1,num2,num3; //方法 public void loadFrame(){ num1 = new TextField(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); setVisible(true); pack(); } } //*** class MyCalculatorListener implements ActionListener { //获取计算器这个变量,在一个类中组合另外一个类 Calculator calculator=null; private TextField num1,num2,num3; //把整个 public MyCalculatorListener( Calculator calculator) { this.calculator=calculator; } @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 int n1= Integer.parseInt(calculator.num1.getText()); int n2= Integer.parseInt(calculator.num2.getText());//文本框内由string转换 //加法运算后放到第三个框内 calculator.num3.setText(""+(n1+n2)); //清除前三个框 calculator.num1.setText(""); calculator.num2.setText(""); } }
内部类:
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 TextCalc { public static void main(String[] args) { new Calculator().loadFrame(); } } //计算器类 class Calculator extends Frame{ //属性 TextField num1,num2,num3; //方法 public void loadFrame() { num1 = new TextField(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); setVisible(true); pack(); } //***类 //内部类的好处就是可以畅通无阻的访问外部类 private class MyCalculatorListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { //1.获得加数和被加数 int n1= Integer.parseInt(num1.getText()); int n2= Integer.parseInt(num2.getText());//文本框内由string转换 //加法运算后放到第三个框内 num3.setText(""+(n1+n2)); //清除前三个框 num1.setText(""); num2.setText(""); } } }