Question

I'm trying to follow MVC concepts when i develop my application ,but I'm confused between Using String or StringProperty in Model classes.

Example one :

public class User{

    String name;
    String password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

Example Two:

public class User{

    StringProperty name;
    StringProperty password ;

    public StringProperty getName() {
        return name;
    }

    public void setName(StringProperty name) {
        this.name = name;
    }

    public StringProperty getPassword() {
        return password;
    }

    public void setPassword(StringProperty password) {
        this.password = password;
    }

    public User(StringProperty name, StringProperty password) {
        this.name = name;
        this.password = password;
    }

I'm using example one ,Is there difference between these models or are they the same ?

Était-ce utile?

La solution

A JavaFX property is an observable container that facilitates data binding: The view can be connected with properties in the view model, so that it automatically updates when the model is changed.

So – use property fields if you want data binding, use ordinary strings when you don't need data binding.

In any case, the property should be bound to a specific model object. You should see a property as a special kind of variable, not as an ordinary object. So passing a property in a setter or in a constructor is highly unusual. Instead, your getters, setters and constructors would usually operate on the data stored within a property. This way, your property-based classes can also be used as Java Beans.

E.g. code using a property might look like this:

public class User{
    private StringProperty nameProperty = new StringProperty();

    public final String getName() {
        return nameProperty.get();
    }

    public final void setName(String name) {
        nameProperty.set(name);
    }

    // expose the property for data binding
    // – possibly use a read-only interface
    public StringProperty nameProperty() {
        return nameProperty;
    }

    public User(String name) {
        nameProperty.set(name);
    }
}

Autres conseils

One difference that should be noted is JavaFX properties are not Serializable. See @jewelsea answer here.

Licencié sous: CC-BY-SA avec attribution
scroll top