addPropertyChangeListener method in Java
I have implem开发者_如何学JAVAented this method to change the value of a PropertyChangeSupport that is being utilized by an actionPerformed method. However, I run into a NullPointerException because the PropertyChangeSupport instance is null . Can anyone tell me the problem? Below are the code snippets.
For the PropertyChangeListener:
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
if (pcs == null) {
pcs = new PropertyChangeSupport(this);
}
this.pcs.addPropertyChangeListener(listener);
}
For the event:
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();
}
It's probably because you are calling this.pcs.firePropertyChange(PROP_TASK, oldTask,this.task);
before you've called whatever class that instantiates the PropertyChangeSupport (pcs) in its addPropertyChangeListener() method. i.e. the bottom block of code is getting called before the top (if at all) gets called. You could try checking if pcs is null in the jButtonActionPerformed() method and instantiating there.
Seems to be a missing call in the constructor:
public TaskEditorPanel() {
if (null == this.taskMgr) {
this.taskMgr = Lookup.getDefault().lookup(TaskManager.class);
}
if (null != this.taskMgr) {
this.task = this.taskMgr.createTask();
}
initComponents();
this.updateForm();
// missed call
this.pcs = new PropertyChangeSupport(this);
}
精彩评论