JavaFx可编辑表格视图

时间:2018-07-20 04:36:40

标签: java javafx tableview javafx-8

我正在尝试编写一个简单的应用程序,该应用程序从DB检索数据并将其写回到DB。我使用javafx,试图在表格视图中列出数据并能够对其进行编辑。但是无法使可编辑选项起作用。请参阅以下错误说明。这里给出了错误。

id.setCellFactory(TextFieldTableCell.<Person>forTableColumn());//It gives error here.



public class Person {

    private int id;


     public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }   

}

public class PersonController 
{
    @FXML
    private TableView<Person> personGrid;

    private ObservableList<Person> dataPerson;  
    dataPerson = FXCollections.observableArrayList();
    Person person;

    try {
        statement = dbConnection.connectToDB().prepareStatement(
                "SELECT ID FROM PERSON");

        ResultSet queryResult = statement.executeQuery();
        while (queryResult.next()) {
            person = new Person();
            person.setId(queryResult.getInt("id"));
            dataPerson.add(person);
        }
        personGrid.setItems(dataPerson);        


    personGrid.setEditable(true);
    TableColumn<Person, Integer> id = new TableColumn("ID");
        id.setCellValueFactory(new PropertyValueFactory("id"));
        id.setCellFactory(TextFieldTableCell.<Person>forTableColumn()); 
// Here I get the error  javafx.util.Callback<javafx.scene.control.TableColumn<org.core.Person, java.lang.Integer>,javafx.scene.control.TableCell<org.core.Person, java.lang.Integer>>
                in TableColumn cannot be applied to javafx.util.Callback<javafx.scene.control.TableColumn<org.core.Person, java.lang.String>,javafx.scene.control.TableCell<org.core.Person, java.lang.String>>. As its seen my field type is int I do not understand why it keeps saying String. 

//Also I tried it this way. It does not give error msg. But cannot edit into cell when I double click.

        TableColumn<Person, Integer> id = new TableColumn("ID");
        id.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, Integer>, ObservableValue<Integer>>() {
            public ObservableValue<Integer> call(TableColumn.CellDataFeatures<Person, Integer> p) {
                return new SimpleIntegerProperty( p.getValue().getId()).asObject();
            }
        });             


        id.setOnEditCommit(
                (TableColumn.CellEditEvent<Person, Integer> cell) -> {
                    ((Person) cell.getTableView().getItems().get(
                            cell.getTablePosition().getRow())
                    ).setId(cell.getNewValue());
                });



    personGrid.getColumns().addAll(id);                 

}

0 个答案:

没有答案