问题
I tried to populate a tableView
, I followed the tutorial given in docs.oracle, but in my table there are Integer
fields, so I do the same thing to add them.
The code in the information class (like Person
class):
private SimpleIntegerProperty gel;
public int getGel() {
return gel.get();
}
public void setGel(int pop) {
gel.set(pop);
}
The code in the Main
class:
TableColumn gel = new TableColumn("Gel");
gel.setMinWidth(100);
gel.setCellValueFactory(new PropertyValueFactory<Information, Integer>("gel"));
gel.setCellFactory(TextFieldTableCell.forTableColumn());
gel.setOnEditCommit(new EventHandler<CellEditEvent<Information, Integer>>() {
@Override
public void handle(CellEditEvent<Information, Integer> t) {
((Information) t.getTableView().getItems()
.get(t.getTablePosition().getRow()))
.setGel(t.getNewValue());
}
});
but I have errors:
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at javafx.util.converter.DefaultStringConverter.toString(DefaultStringConverter.java:34)
at javafx.scene.control.cell.CellUtils.getItemText(CellUtils.java:100)
at javafx.scene.control.cell.CellUtils.updateItem(CellUtils.java:201)
at javafx.scene.control.cell.TextFieldTableCell.updateItem(TextFieldTableCell.java:204)
回答1:
The problem is in your cell factory.
TableColumn
should be typed to TableColumn<Information, Integer>
. Then you will see an error here:
gel.setCellFactory(TextFieldTableCell.forTableColumn());
(the same error you have on runtime). The reason is the static callback forTableColumn
is only for TableColumn
of type String.
For other types you have to provide a custom string converter. This will solve your problems:
gel.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<Integer>(){
@Override
public String toString(Integer object) {
return object.toString();
}
@Override
public Integer fromString(String string) {
return Integer.parseInt(string);
}
}));
来源:https://stackoverflow.com/questions/27468546/how-to-use-simpleintegerproperty-in-javafx