A good way to stay flexible is to write less code. --Pragmatic Programmer

By , on November 26, 2009

Development, Java, JavaFX

Tags: , ,


Data binding in JavaFX is pretty straightforward.
You should think binding to Java Objects should be just as simple, well it is a little complicater then just doing

var someObject : bind myJavaclass.getProperty();

JavaFX needs to be aware of any changes to the bound variables to be able to update the related objects. It does this automagically for all javafx objects.
It seems JavaFX uses the Observer/Observable pattern for all its internal objects, well we can do the same to bind with JavaObjects.
To get myself familiar with JavaFX i decided to write a photoviewer/editor. This application has a java backend with in particular a Photo class which contains all the information of a certain picture, filename, path, tags, exif information etcetera

To get changes in the Java class to appear in the gui I create a PhotoAdapter javafx class that extends Observer and implemented the properties I need in my GUI.

public class PhotoAdapter extends Observer {
    public-read var filename: String;
    public-read var tags: String[];
    public-read var exif: String[];
 
    public-init var photo: Photo
         on replace {
            photo.addObserver(this);
            filename=photo.getFilename();
            tags = photo.getTags();
            exif = photo.getExif();
         };
 
    override function update(observable: Observable, arg: Object) {
        filename = photo.getFilename();
        tags = photo.getTags();
        exif = photo.getExif();
    }

after that I had my existing Java Photo class extend Observable and in every method that made changes I added the methods setChanged() and NotifyObservers() to inform the Observers about the change

public class Photo extends Observable {
    private Map<String, String> exifInformation; 
    ....
    public void setExifInformation(Map exifInfo) {
        this.exifInformation = exifInfo;
        setChanged();
        notifyObservers();
    }
}

in my main javafx class I can then use it as follows

    var photoAdapter = PhotoAdapter {
        photo : new Photo(startImage);
}

and use to fill a ListView swing object with for instance the tags:

    ListView {
        items:     bind photoAdapter.tags;
        width:     200;
        height:    300;
    }

et viola, thats all that there is to it



Comments are closed.