添加并选择TableView中的ChoiceBox

时间:2018-03-28 19:51:34

标签: java xml javafx fxml

所以我试图为TableView中插入的每个变量添加一个ChoiceBox。

Users.java:

 Users(String userName , Integer userAge , ChoiceBox employed)
{
    this.userName = userName ;
    this.userAge = userAge ;
    this.employed= employed;
}
//getters and setters

Main.java:

ObservableList<Users>userList = FXCollections.observableArrayList();
TableView<Users> userTable = new TableView();
TableColumn<Users, String> nameCol = new TableColumn();
TableColumn<Users, Integer> ageCol = new TableColumn();

TableColumn<Users, ChoiceBox> employCol = new TableColumn();

private ChoiceBox createBox(){ 
ChoiceBox box = new ChoiceBox();
box.getItems.addAll("true" , "false");
box.setValue("true"); 
return box;
}


userList.addAll(new User("James" , 47 , createBox()));

Everything编译并运行得很好,但我无法获得用户点击的box的引用。我尝试通过选择模型获得它:

userTable.getSelectionModel().getSelectedItem().employed;

但这只是给了我一个NullPointerException。如果用户选择&#34; true&#34;我需要能够选择选择框。 ,然后它会显示在文本字段中,但这很容易解决,我实际上无法将实例带到选择框。我已经提到过:

Getting selected item from a JavaFX TableView

javafx: attach ChoiceBox to a TableCell on a TableColumn during Edit

ChoiceBox with custom Item in a TableView

但无济于事。我也试过使用多种变体

ChoiceBoxTableCell

ChoiceBoxTableList

但是这些甚至无法编译,我不断收到回调错误。

1 个答案:

答案 0 :(得分:0)

Callback<TableColumn<Users, String>, TableCell<Users, String>> cellFactory
            = //
            new Callback<TableColumn<Users, String>, TableCell<Users, String>>() {
        @Override
        public TableCell call(final TableColumn<Users, String> param) {
            final TableCell<Users, String> cell = new TableCell<Users, String>() {

                final ChoiceBox createBox(){ 
ChoiceBox box = new ChoiceBox();
box.getItems.addAll("true" , "false");
box.setValue("true"); 

                @Override
                public void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                        setText(null);
                    } else {
                        setGraphic(createBox);
                        setText(null);
                    }
                }
            };
            return cell;
        }
    };

    employCol.setCellFactory(cellFactory);