AWTEventMulticaster在管理TextListener时出现问题, 请专家解答

rui1983YY 2008-04-21 08:39:57
专家你好:
我写了下面的代码,想利用AWTEventMulticaster来添加TextListener,实现文本监听,
但实现不了。不打印bbbb,这是说明t_Listener为空吧?
直接对lab1添加监听器时是可以达到目的的。
请问要怎么修改?原因是什么呢?

public class Test extends Applet {
private TextListener Listener =null;
private TextListener t_Listener=null;
private TextField lab1 = new TextField();
private AudioClip aud1 = null;
private AudioClip aud2 = null;

public synchronized void addTextListener(TextListener t) {
t_Listener = AWTEventMulticaster.add(t_Listener, t);
}
public synchronized void removeTextListener(TextListener t) {
t_Listener = AWTEventMulticaster.remove(t_Listener, t);
}

protected void processEvent(AWTEvent e) {
if (e instanceof TextEvent) {
processTextEvent((TextEvent) e);
return;
}
super.processEvent(e);
}

protected void processTextEvent(TextEvent e) {
System.out.println("aaaa");
if (t_Listener != null) {
System.out.println("bbbb");
t_Listener.textValueChanged(e);
}
}

// lab1.addTextListener(new TextListener(){
protected void textValueChanged(TextEvent e) {
if (lab1.getText().equals("1")) {
aud1 = getAudioClip(getDocumentBase(), "mianban/alert2.wav");
aud1.play();
} else {
AudioClip aud2 = getAudioClip(getDocumentBase(),"mianban/alert5.wav");
aud2.play();
}
}

public void init() {
try {
FlowLayout flowLayout = new FlowLayout();
setBackground(Color.lightGray);
setLayout(flowLayout);
add(lab1);
lab1.setBackground(Color.blue);
//lab1.setText("1");
processEvent(new TextEvent(lab1, TextEvent.TEXT_VALUE_CHANGED));
setVisible(true);

} catch (RuntimeException e) {
e.printStackTrace();
}
}
...全文
99 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenweionline 2008-04-22
  • 打赏
  • 举报
回复
TextListener是个接口,你需要自己创建一个类实现这个接口。
rui1983YY 2008-04-22
  • 打赏
  • 举报
回复
我尝试这样子给它实例化
private TextListener t_Listener=new TextListener();
但是会报错:不能实例化类型TextListener;
这个我也感觉是不能这么实例化,TextListener是个接口,
不这样的话要怎么初始化呢?我不会,还请指点
rui1983YY 2008-04-22
  • 打赏
  • 举报
回复
好吧,谢谢!
chenweionline 2008-04-21
  • 打赏
  • 举报
回复
简单的看了下,你的程序里在调用processTextEvent()前好像并没有初始化t_Listener,那么t_Listener当然是null了。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧