import java.awt.*;
import java.awt.event.*;
class MyWindow extends Frame implements ActionListener
{ TextField text1,text2,text3;
MyWindow()
{ setLayout(new FlowLayout());
text1=new TextField(8);
text2=new TextField(8);
text3=new TextField(15);
add(text1);
add(text2);
add(text3);
text1.addActionListener(this);//这里两个this是指win吗?为什么不能写win?不用this还可以怎么写?
text2.addActionListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==text1)
{ String word=text1.getText();
if(word.equals("boy"))
{ text3.setText("男孩");
}
else if (word.equals("girl"))
{ text3.setText("女孩");
}
else if (word.equals("sun"))
{ text3.setText("太阳");
}
else
{ text3.setText("没有该单词");
}
}
else if(e.getSource()==text2)
{ String word=text2.getText();
if(word.equals("男孩"))
{ text3.setText("boy");
}
else if (word.equals("女孩"))
{ text3.setText("girl");
}
else if (word.equals("太阳"))
{ text3.setText("sun");
}
else
{ text3.setText("没有该单词");
}
}
}
}
public class Example7_3
{ public static void main(String args[])
{ MyWindow win=new MyWindow();
}
}
public void actionPerformed(ActionEvent ae){
}
});
就是你運行到這一步時候的對象就是this,就是說你運行到這步,程序中的對象是什么,this就是什么
這里也就是win
{
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==text1)
{ String word=text1.getText();
if(word.equals("boy"))
{ text3.setText("男孩");
}
else if (word.equals("girl"))
{ text3.setText("女孩");
}
else if (word.equals("sun"))
{ text3.setText("太阳");
}
else
{ text3.setText("没有该单词");
}
}
else if(e.getSource()==text2)
{ String word=text2.getText();
if(word.equals("男孩"))
{ text3.setText("boy");
}
else if (word.equals("女孩"))
{ text3.setText("girl");
}
else if (word.equals("太阳"))
{ text3.setText("sun");
}
else
{ text3.setText("没有该单词");
}
}
}
}
然后在添加事件处理对象时,可以这样写MyActionListener xxx=new MyActionListener;
text1.addActionListener(xxx);
text2.addActionListener(xxx);
效果是一样的.当然也可以采用基于实现匿名内部类的方法,直接在addActionListener方法的实例参数中给出事件处理接口的实现.
本例可以写为 text1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==text1)
{ String word=text1.getText();
if(word.equals("boy"))
{ text3.setText("男孩");
}
else if (word.equals("girl"))
{ text3.setText("女孩");
}
else if (word.equals("sun"))
{ text3.setText("太阳");
}
else
{ text3.setText("没有该单词");
}
}
else if(e.getSource()==text2)
{ String word=text2.getText();
if(word.equals("男孩"))
{ text3.setText("boy");
}
else if (word.equals("女孩"))
{ text3.setText("girl");
}
else if (word.equals("太阳"))
{ text3.setText("sun");
}
else
{ text3.setText("没有该单词");
}
}
}
}
);
但是这种方法仅限于该事件处理只添加于单个空间中,如果多个控件使用同一个事件处理对象时,使用这个方法就就不太适合,而且这个方法我在学的时候经常会造成几个括号多了或者漏了的错误.班门弄斧一下,希望各位大侠批评指正.
请问九楼,一下这句有和原因
addActionListener这个方法的形参是实现了ActionListener接口类的对象???