package com.zym.lesson9; import javax.swing.*; 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 TestCalc { public static void main(String[] args) { new Calculator(); } } //计算器类 class Calculator extends JFrame { //构造器 public Calculator() { //三个文本框 TextField num1 = new TextField(10); TextField num2 = new TextField(10); TextField num3 = new TextField(20); //一个按钮 Button button = new Button("="); //对按钮添加一个事件 button.addActionListener(new MyCalculatorListener(num1,num2,num3)); //一个标签 Label label = new Label("+"); //流式布局 setLayout(new FlowLayout()); //添加组件 add(num1); add(label); add(num2); add(button); add(num3); //自适应大小 pack(); //设置可见 setVisible(true); addWindowListener(new WindowAdapter() { //窗体关闭时做的事 @Override public void windowClosing(WindowEvent e) { // super.windowClosed(e); System.exit(0); } } ); } } //监听器类 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; } @Override public void actionPerformed(ActionEvent e) { // 1获得加数与被加数 //num1.getText() //Integer.getInteger() int n1= Integer.parseInt(num1.getText()); int n2= Integer.parseInt(num2.getText()); // 2 将这个值加法运行后,放到第三个框中 num3.setText(""+(n1+n2)); // 3 清除前两个框 num1.setText(""); num2.setText(""); } }
标签:num1,num2,num3,import,lesson9,简易,计算器,new,TextField From: https://www.cnblogs.com/zym97816/p/17745726.html