这里先吐槽一下研究生读心累,没事还是别考研,Java进度越来越慢,学到内部类就实现了一个文本框相加:
import java.awt.*;
import java.awt.event.*;
public class TestText {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tf tf=new Tf();//只需要创建一个Tf类
tf.launch();//然后调用之前存放主方法的代码函数
}
}
class Tf{
private TextField t1,t2,t3;
public void launch()//定义一个方法让主方法中间代码尽可能少
{
Frame f=new Frame("渐渐计算机");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
Label Lb=new Label("+");
Button bn=new Button("=");
f.setLayout(new FlowLayout());
f.add(t1);
f.add(Lb);
f.add(t2);
f.add(bn);
f.add(t3);
bn.addActionListener(new MyAction());//实现事件监听类的对象
f.addWindowListener(new MyAction());//同上
f.pack();
f.setVisible(true);
}
class MyAction implements ActionListener,WindowListener//实现事件的类,该类为内部类
{
public void actionPerformed(ActionEvent e)//抽象类中方法的重写
{
//因为对象t1,t2 t3都是静态属性,所以可以直接使用类名方法调用 ,又因为getText方法是返回一个String类型,所以需要顶一个Sring的变量来接受
String str1=t1.getText();//因为这里t1,t2,t3是外部类的属性,则可以直接访问
String str2=t2.getText();
int num1=Integer.parseInt(str1);//这里是使用Integer类中ParseInt方法将String类型转化成int,其中接受参数为String类型,返回int型
int num2=Integer.parseInt(str2);
int result=num1+num2;
t3.setText(result+" ");//这里先创建一个Intger的一个对象用result来初始化,然后这个对象再调用toString方法转换成字符串类型
//因为setText方法接受参数为字符串类型
}
public void windowClosing(WindowEvent e)//关闭
{
System.exit(0);
}
public void windowOpened(WindowEvent e){};
public void windowIconified(WindowEvent e){};//最小化
public void windowDeiconified(WindowEvent e){}; //最大化
public void windowClosed(WindowEvent e){};
public void windowActivated(WindowEvent e){};
public void windowDeactivated(WindowEvent e){};
}
}