日期:2014-05-20 浏览次数:20845 次
import java.awt.*;
import java.awt.event.*;
public class TestTextField
{
public static TextField tf1, tf2, tf3; //静态的三个文本框类型的变量,
//这里必须是静态的以便另外一个类能访问
public static void main(String[] args)
{
TextField tf1 = new TextField(30); //30表示文本框的长度;
TextField tf2 = new TextField(30);
TextField tf3 = new TextField(30);
Button bn = new Button("=");
Label lb = new Label("+");
Frame f = new Frame("文本框相加示例");
f.setLayout(new FlowLayout()); //设置容器为流式布局
f.add(tf1);
f.add(lb);
f.add(tf2);
f.add(bn);
f.add(tf3);
bn.addActionListener(new MyMonitor()); //将等号按钮添加一个监视器
f.addWindowListener(new B()); //给容器f添加一个监视器,用来关闭window窗口
f.pack();
f.setVisible(true);
}
}
class MyMonitor implements ActionListener
{
@Override //这里的作用可以增加程序的安全性,保证了下面的方法是调用重写的而不是父类的
public void actionPerformed(ActionEvent e)
{
String str1 = TestTextField.tf1.getText();
String str2 = TestTextField.tf2.getText(); //两个文本框接受两个数
int num1 = Integer.parseInt(str1);
int num2 = Integer.parseInt(str2); //将文本框接收的数据转化为整型的
int num3 = num1 + num2;
Integer it = new Integer(num3);
String str3 = it.toString(); //将结果转化为String类型的输出
TestTextField.tf3.setText(str3);
}
}
class B extends WindowAdapter //设置window窗口关闭按钮事件
{
public void windowClosing(WindowEvent e)
{
System.exit(-1);
}
}