日期:2014-05-20  浏览次数:20722 次

文本框上的ActionEvent事件的小问题
此程序的目的是实现两个文本框(text1、text2)中值的和在text3中输出。



Java code
import java.awt.*;
import java.awt.event.*;
class MyWindow extends Frame implements ActionListener{
    TextField text1,text2,text3;
    PoliceMan police;
    int n1,n2;
    MyWindow(){
        text1=new TextField(10);
        text2=new TextField(10);
        text3=new TextField(10);
        police=new PoliceMan();
        setLayout(new FlowLayout());
        add(text1);
        add(text2);
        add(text3);
        text1.addActionListener(police);
        text2.addActionListener(this);
        setBounds(300,300,150,150);
        setVisible(true);
        validate();
    }
    public void actionPerformed(ActionEvent e){
        //String number1=e.getActionCommand();        
        String number2=e.getActionCommand();
        //int n1=Integer.parseInt(number1);
        int n2=Integer.parseInt(number2);
        int sum=n1+n2;
        text3.setText(n1+"+"+n2+"="+sum);
    }
}
class PoliceMan implements


运行结果:
输入text1:1
  text2:2
  text3:0+2=2//不能获取text1中的值,总是获取0!
我是想用text1的监视器的实现把它发生事件时的那个输入的值先用个变量存储下来,再等待text2发生事件时求他们的值,并把它们的和显示在text3中。
不知我这个想法能否很好的实现?另:各位也可以用其他的方法帮我解决一下:)提前谢谢各位哈~~~

------解决方案--------------------
这样就好了
import java.awt.*;
import java.awt.event.*;
class MyWindow extends Frame implements ActionListener
{
TextField text1,text2,text3;
PoliceMan police;
int n2;

MyWindow(){
text1=new TextField(10);
text2=new TextField(10);
text3=new TextField(10);
police=new PoliceMan();
setLayout(new FlowLayout());
add(text1);
add(text2);
add(text3);
text1.addActionListener(police);
text2.addActionListener(this);
setBounds(300,300,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e){
String number2=e.getActionCommand();
int n2=Integer.parseInt(number2);
int sum=police.n1+n2;
text3.setText(police.n1+"+"+n2+"="+sum);
}
}

class PoliceMan implements ActionListener
{
int n1;
public void actionPerformed(ActionEvent e)
{
String number1=e.getActionCommand();
n1=Integer.parseInt(number1);
}
}

public class TextField1 
{
public static void main(String[] args)
{
MyWindow win=new MyWindow();
}
}