我正在编写一个程序来管理和显示有关机场,其航类等的数据。
事实是,我有一个tableView(在javafx中)带有几个tableColumns,并且我想在每列上显示一些信息(目的地,来源,公司等),所以我输入了以下内容:
@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());
}
它说的
getDestiny()
方法以String
的形式返回特定航类的目的地,因此很显然我不能使用最后一条指令,它说cannot convert from String to ObservableValue<String>
但是我真的不知道如何解决它,以便能够在那一栏上显示命运。
最佳答案
根据Javadocs,setCellValueFactory(...)
需要一个Callback<CellDataFeatures<Flight, String>, ObservableValue<String>>
,即以CellDataFeatures<Flight, String>
作为其参数并产生ObservableValue<String>
的函数。
如错误消息所述,您的函数计算出的String
(cellData.getValue().getDestiny()
)不是正确的类型。
您有两种选择,具体取决于您的实际需求。
您可以即时创建正确类型的东西:最容易使用的是 ReadOnlyStringWrapper
:
destinoCol.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getDestiny()));
这将显示正确的值,但不会很好地“连接”到飞行对象的属性。如果您的表是可编辑的,则编辑不会自动传播回基础对象,并且从其他位置对基础对象所做的更改也不会在表中自动更新。
如果需要此功能(无论如何,这可能是一种更好的方法),则应实现模型类
Flight
以使用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...
}
然后你可以做
destinoCol.setCellValueFactory(cellData -> cellData.getValue().destinyProperty());
关于javafx - 无法从String转换为ObservableValue <String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30334450/