一个简单的例子,实现简单的输入加法运算
import java.awt.*;
import java.awt.event.*;
public class Monitor3Test {
public static void main(String[] args) {
TFMath f = new TFMath();
}
}
class TFMath extends Frame{
TextField num1,num2,num3;
TFMath(){
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(15);
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(15);
Label l1 = new Label("+");
Button b1 = new Button("=");
// b1.addActionListener(new ButtonListener(this));
b1.addActionListener(new ButtonListener(num1, num2, num3));
this.setLayout(new FlowLayout());
add(num1);
add(l1);
add(num2);
add(b1);
add(num3);
this.setBackground(Color.blue);
this.setBounds(200, 200, 200, 200);
this.setVisible(true);
}
}
class ButtonListener implements ActionListener{
TextField num1,num2,num3;
TFMath f = null;
public ButtonListener(TextField num1,TextField num2, TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
/*
public ButtonListener(TFMath f) {
this.f = f;
}
*/
public void actionPerformed(ActionEvent e) {
// int n1 = Integer.parseInt(f.num1.getText());
// int n2 = Integer.parseInt(f.num2.getText());
// f.num3.setText("" + (n1+n2));
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText("" + (n1+n2));
}
}
主要的部件有三个个可输入文本(TextField)组件用来接收输入和输出数据,一个固定符号(Label),一个按键触发器(Button),用来触发事件,但是其中有一点需要注意,输入数据是在TFMath类中完成的,其是TFMath类的数据,如何让Monitor获得,
提供了两套方法,一种方法:
在调用Monitor的构造方法时,直接把对象中的变量传给Monitor,相当于数据的一种复制,我们把调用类的数据copy到被调类中,
另一种方法:
在调用Monitor的构造方法时,直接把对象传给Monitor,即在被调用的类中有了一个完整的调用类的对象的引用,可以直接通过对象的引用获取数据。
注:第一种方法,不需要要求num(即被处理数据)是成员变量,但是,第二种方法必须要求其为成员变量。不然无法直接用对象进行调用。
我们在被调用类中得到的是一个TextField类,我们通过Interger.parseInt把一个String类型的数据转换成一个Int类型。
TextField类中的setText的参数是String类型,所以我们用“”+Int类型的数进行转换。