cannot convert from String to ObservableValue<String>

泄露秘密 提交于 2019-11-29 07:04:48

According to the Javadocs, setCellValueFactory(...) expects a Callback<CellDataFeatures<Flight, String>, ObservableValue<String>>, i.e a function that takes a CellDataFeatures<Flight, String> as its parameter, and results in an ObservableValue<String>.

As the error message says, your function evaluates to a String (cellData.getValue().getDestiny()), which is not the correct type.

You have two choices, depending on your actual requirements.

Either you can create something on the fly that is of the correct type: the easiest thing to use is a ReadOnlyStringWrapper:

destinoCol.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getDestiny()));

This will display the correct value, but won't be nicely "wired" to the property of the flight object. If your table is editable, edits won't automatically propagate back to the underlying object, and changes to the underlying object from elsewhere won't automatically update in the table.

If you need this functionality (and this is probably a better approach anyway), you should implement your model class Flight to use JavaFX properties:

public class Flight {

    private final StringProperty destiny = new SimpleStringProperty();

    public StringProperty destinyProperty() {
        return destiny ;
    }

    public final String getDestiny() {
        return destinyProperty().get();
    }

    public final void setDestiny(String destiny) {
        destinyProperty().set(destiny);
    }

    // similarly for other properties...
}

and then you can do

destinoCol.setCellValueFactory(cellData -> cellData.getValue().destinyProperty());

I am a bit late I think, but this might help others. You can have cade as below

destinoCol.setCellValueFactory(cellData -> cellData.getValue().destinyProperty().asObject());

This code will work for property other than string, as I had problem with "LongProperty".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!