从另一个问题开始,我提出了一个Singleton Observable。为什么不执行ArticleSelect.update()?
package net.bounceme.dur.usenet.swing;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import javax.swing.ListModel;
import net.bounceme.dur.usenet.controller.ArticleDefaultListModel;
import net.bounceme.dur.usenet.controller.Controller;
public class ArticleSelect extends javax.swing.JPanel implements Observer {
private static final Logger LOG = Logger.getLogger(ArticleSelect.class.getName());
private Controller controller = Controller.getInstance();
private ListModel defaultListModel = new ArticleDefaultListModel();
public ArticleSelect() {
controller.addObserver(this);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setLayout(new java.awt.BorderLayout());
jList1.setModel(defaultListModel);
jScrollPane1.setViewportView(jList1);
add(jScrollPane1, java.awt.BorderLayout.WEST);
jScrollPane2.setViewportView(jTextPane1);
add(jScrollPane2, java.awt.BorderLayout.CENTER);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
@Override
public void update(Observable o, Object arg) {
LOG.info("trying to observe.." + arg);
LOG.info(controller.getGroup());
//update defaultListModel
}
}
扩展Observe的对象从Controller.setGroup()调用notifyObserver:
package net.bounceme.dur.usenet.controller;
import java.util.Observable;
import java.util.logging.Logger;
public class Controller extends Observable {
private static final Logger LOG = Logger.getLogger(Controller.class.getName());
private String group;
private static Controller instance;
protected Controller() {
}
public static Controller getInstance() {
if (instance == null) {
instance = new Controller();
}
return instance;
}
public void setGroup(String selectedValue) {
group = selectedValue;
LOG.fine(group);
notifyObservers();
}
public String getGroup() {
return group;
}
}
也许ArticleSelect没有正确注册以观察Controller?
java.util.Observable#notifyObservers()
只有当对象注册为已用setChanged()
更改时,才会调用update()
方法。