无法从String转换为ObservableValue <String>

JOS*_*UEN 8 javafx tableview tablecolumn

我正在制作一个程序来管理和显示有关机场,航班等的数据.事实是我有一个带有几个tableColumns的tableView(在javafx中),我想在每列上显示一些信息(命运,起源,公司等),所以我键入了这个:

@FXML
private TableColumn<Flight, String> destinoCol;

@FXML
private TableColumn<Flight, String> numCol;

@FXML
private MenuButton aeropuerto;

@FXML
private MenuButton tipo;

@FXML
private Button filtrar;

@FXML
private TableColumn<Flight, LocalTime> horaCol;

@FXML
private Button este;

@FXML
private DatePicker fecha;

@FXML
private TableColumn<Flight, String> origenCol;

@FXML
private Label retrasoLabel;

@FXML
private ImageView companiaImg;

@FXML
private VBox detalles;

@FXML
private Button todos;

@FXML
private ImageView avionImg;

@FXML
private Label tipoLabel;

private mainVuelos m;
private List<Airport> aeropuertos;
private Data data;
@FXML
void initialize() {
    data = Data.getInstance();
    aeropuertos = data.getAirportList();
    List<MenuItem> ItemAeropuertos = new LinkedList<MenuItem>();
    for (int i = 0; i < aeropuertos.size(); i++) {
        MenuItem item = new MenuItem(aeropuertos.get(i).getName());
        item.setOnAction((event) -> cambiarAer(event));
        ItemAeropuertos.add(item);
    }
    aeropuerto.getItems().setAll(ItemAeropuertos);
    destinoCol.setCellValueFactory(cellData -> cellData.getValue().getDestiny());
}
Run Code Online (Sandbox Code Playgroud)

方法getDestiny(),因为它表示将特定航班的命运作为String返回,所以很明显我不能使用最后一条指令,它说"无法从String转换为ObservableValue",但我真的不知道如何解决它为了能够显示该列的命运.谢谢大家.

Jam*_*s_D 12

根据Javadocs,setCellValueFactory(...)期望a Callback<CellDataFeatures<Flight, String>, ObservableValue<String>>,即一个以a CellDataFeatures<Flight, String>为参数的函数,并产生一个ObservableValue<String>.

正如错误消息所示,您的函数求值为a String(cellData.getValue().getDestiny()),这不是正确的类型.

您有两种选择,具体取决于您的实际要求.

您可以动态创建具有正确类型的东西:最简单的方法是使用ReadOnlyStringWrapper:

destinoCol.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getDestiny()));
Run Code Online (Sandbox Code Playgroud)

这将显示正确的值,但不会很好地"连线"到飞行对象的属性.如果您的表是可编辑的,则编辑不会自动传播回底层对象,并且从其他位置对基础对象的更改不会自动在表中更新.

如果您需要此功能(这可能是一种更好的方法),您应该实现您的模型类Flight以使用JavaFX属性:

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...
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以做到

destinoCol.setCellValueFactory(cellData -> cellData.getValue().destinyProperty());
Run Code Online (Sandbox Code Playgroud)


小智 5

我想我有点晚了,但这可能会帮助其他人。你可以有 cade 如下

destinoCol.setCellValueFactory(cellData -> cellData.getValue().destinyProperty().asObject());
Run Code Online (Sandbox Code Playgroud)

此代码适用于字符串以外的属性,因为我遇到了“LongProperty”问题。