我们可以用文本框来存数值,点击“”=“”在最后的文本框中打印结果,那么一定是给等号按钮设置监听,
那么我们怎么将其他文本框中的值,传递过来呢。最笨的方法是用到什么就传递进去什么(在new监听器的时候)。当然不如直接的将整个this本身传递进去好了。
package awt;
import java.awt.*;
public class graphy {
public static void main(String[] args){
new TFframe().launchFrame();
}
}
package awt;
import java.awt.*;
import java.awt.event.*;
public class TFframe extends Frame {
TextField num1,num2,num3;
public void launchFrame(){
num1 = new TextField(20);
num2= new TextField(20);
num3 = new TextField(20);
Label Plus = new Label("+");
Button equals = new Button("=");
setLayout(new FlowLayout());
add(num1);add(Plus);add(num2);
add(num2);add(equals);add(num3);
//equals.addActionListener(new Monitor(num1,num2,num3));
equals.addActionListener(new Monitor(this));
setVisible(true);
pack();
}
}
package awt;
import java.awt.*;
import java.awt.event.*;
public class Monitor implements ActionListener{
/*TextField num1,num2,num3;
Monitor(TextField nu1,TextField nu2,TextField nu3){
this.num1 = nu1;
this.num2 = nu2;
this.num3 = nu3;
}*/
TFframe tf = null;
public Monitor(TFframe tf){
this.tf = tf;
}
public void actionPerformed(ActionEvent e){
//System.out.println("heihie");
//int n1 = Integer.parseInt(num1.getText());
//int n2 = Integer.parseInt(num2.getText());
//num3.setText(String.valueOf((n1+n2)));
int n1 = Integer.parseInt(tf.num1.getText());
int n2 = Integer.parseInt(tf.num2.getText());
tf.num3.setText(String.valueOf((n1+n2)));
}
}