Adding and selecting ChoiceBox that's inside a TableView

拜拜、爱过 提交于 2019-12-25 18:16:07

问题


So I'm trying to add a ChoiceBox for every variable inserted in the TableView.

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 compiles and runs just fine, but I have no way of getting a reference to the box that is clicked by the user. I tried getting it via selection model:

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

but this just gives me a NullPointerException. I need to be able to select the choice box, if the user selects "true" , then it would display in a text field, but that's an easy fix, I'm having trouble actually getting the instance to the choicebox. I've referred to:

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

But to no avail. I've also tried using multiple variations of

ChoiceBoxTableCell

and

ChoiceBoxTableList

but these won't even compile, I keep getting a callback error.


回答1:


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


来源:https://stackoverflow.com/questions/49543019/adding-and-selecting-choicebox-thats-inside-a-tableview

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