Java中的listener addPropertyChangeListener方法
我已经实现了这个方法来更改actionPerformed方法正在使用的PropertyChangeSupport的值。但是,我遇到了NullPointerException,因为PropertyChangeSupport实例是null。谁能告诉我这个问题吗?下面是代码片段
对于PropertyChangeListener:
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
if (pcs == null) {
pcs = new PropertyChangeSupport(this);
}
this.pcs.addPropertyChangeListener(listener);
}
本次活动:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Task oldTask = this.task;
this.task = new TaskImpl();
this.pcs.firePropertyChange(PROP_TASK, oldTask,this.task);
this.updateForm();
}
# 1 楼答案
构造函数中似乎缺少调用:
# 2 楼答案
这可能是因为在调用addPropertyChangeListener()方法中实例化PropertyChangeSupport(pcs)的任何类之前,您正在调用
this.pcs.firePropertyChange(PROP_TASK, oldTask,this.task);
。i、 e.底层代码块在顶层(如果有的话)被调用之前被调用。您可以尝试在jButtonActionPerformed()方法中检查PC是否为null,并在那里进行实例化