使用文本框+按钮+awt,做加法器

我们可以用文本框来存数值,点击“”=“”在最后的文本框中打印结果,那么一定是给等号按钮设置监听,

那么我们怎么将其他文本框中的值,传递过来呢。最笨的方法是用到什么就传递进去什么(在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))); 
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值