添加并选择TableView中的ChoiceBox [英] Adding and selecting ChoiceBox that's inside a TableView
问题描述
所以我正在尝试为TableView中插入的每个变量添加一个ChoiceBox。
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()));
一切都编译并运行得很好,但我无法获得对<$ c的引用$ c> box 由用户点击。我尝试通过选择模型获取它:
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;
但这只是给我一个NullPointerException。我需要能够选择选项框,如果用户选择true,那么它将显示在文本字段中,但这是一个简单的修复,我实际上无法将实例获取到选择框。我已提到:
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:
javafx:在编辑期间将ChoiceBox附加到TableColumn上的TableCell
但无济于事。我也试过使用多种变体
But to no avail. I've also tried using multiple variations of
ChoiceBoxTableCell
和
ChoiceBoxTableList
但这些甚至不会编译,我不断收到回调错误。
but these won't even compile, I keep getting a callback error.
推荐答案
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);
这篇关于添加并选择TableView中的ChoiceBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!