本文介绍了如何在javafx中使用SimpleIntegerProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试填充tableView,我按照docs.oracle中给出的教程,
但是在我的表中有Integer字段,所以我也这样想添加它们:

I tried to populate a tableView, I followed the tutorial given in docs.oracle,But in my table there is Integer fields, so I do the same think to add them:

信息类中的代码(如Person类)

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);
	}

Main类中的代码

 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());
                }
            }
        );

但是我有错误:

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)


解决方案

问题出在你的手机工厂。

The problem is in your cell factory.

TableColumn 应该输入 TableColumn< Information,Integer> 。然后你会在这里看到一个错误:

TableColumn should be typed to TableColumn<Information, Integer>. Then you will see an error here:

gel.setCellFactory(TextFieldTableCell.forTableColumn());

(与运行时相同的错误)。原因是静态回调 forTableColumn 仅适用于String类型的 TableColumn

(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);
        }

    }));

这篇关于如何在javafx中使用SimpleIntegerProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 22:56