How to use SimpleIntegerProperty in JavaFX

限于喜欢 提交于 2019-12-21 22:02:48

问题


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 TableColumnof 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

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