Question

I am trying to implement observer pattern in Java Swing application I am working on as my school project. I have these two very simple classes, one states as a singleton observable model and second is an observer.

Observable model:

public class Model extends Observable {

    private static Model instance = null;
    private File selectedImageFile;
    private int colorsCount;

    public static Logger LOG = Logger.getLogger(Model.class);

    private Model() {
        this.initialize();
    }

    private void initialize() {
        addObserver(new ModelObserver());
    }

    public static Model instance() {
        if (Model.instance == null) {
            Model.instance = new Model();
        }
        return Model.instance;
    }

    public void setColorsCount(int colorsCount) {
        this.colorsCount = colorsCount;
        notifyObservers(Actions.COLORS_COUNT);
    }

    public void selectedImage(File imageFile) {
        this.selectedImageFile = imageFile;
        notifyObservers(Actions.SELECTED_IMAGE);
    }

    public enum Actions {
        SELECTED_IMAGE, COLORS_COUNT
    }

}

Observer

public class ModelObserver implements Observer {

    public static Logger LOG = Logger.getLogger(ModelObserver.class);

    @Override
    public void update(Observable o, Object arg) {

        if (arg instanceof Model.Actions) {

            Model.Actions action = (Actions) arg;

            switch (action) {

            case SELECTED_IMAGE:
                selectedImage();
                break;

            case COLORS_COUNT:
                colorsCount();
                break;

            default:
                LOG.warn("Not supported action: " + action);
                break;
            }

        } else {
            LOG.warn("Not supported action: " + String.valueOf(arg));
        }

    }

    private void colorsCount() {
        LOG.info("Colors count has been changed....");
    }

    private void selectedImage() {
        LOG.info("Image has been changed....");
    }

}

Everything works - Model instance register change but observers (only one in my case) are not notified. In a method ModeObserver.update(Observable o, Object arg) there is no mention that model has been changed. So my problem is that observers are not notified.

What am I doing wrong? Thank you.

Was it helpful?

Solution

You forgot to call setChanged() to mark the observable as changed, which is required by the notifyObservers to actually perform the notification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top