ComboBox in a tableview cell in JavaFX

后端 未结 2 997
一个人的身影
一个人的身影 2021-01-13 11:38

I\'m trying to a add a Combo Box to my Table View:

Basically I have a class called TableViewTest that stores a name and a description, I ca

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 12:30

    James_D's answer works well, but requires the user to click on the item to see the ComboBox. If you want to have ComboBoxes in a column, that are always shown, you have to use a custom cellFactory:

    Example:

    public class TableViewTest {
    
        ...
    
        private final StringProperty option = new SimpleStringProperty();
    
        public String getOption() {
            return option.get();
        }
    
        public void setOption(String value) {
            option.set(value);
        }
    
        public StringProperty optionProperty() {
            return option;
        }
        
    }
    
        TableColumn column = new TableColumn<>("option");
        column.setCellValueFactory(i -> {
            final StringProperty value = i.getValue().optionProperty();
            // binding to constant value
            return Bindings.createObjectBinding(() -> value);
        });
        
        column.setCellFactory(col -> {
            TableCell c = new TableCell<>();
            final ComboBox comboBox = new ComboBox<>(options);
            c.itemProperty().addListener((observable, oldValue, newValue) -> {
                if (oldValue != null) {
                    comboBox.valueProperty().unbindBidirectional(oldValue);
                }
                if (newValue != null) {
                    comboBox.valueProperty().bindBidirectional(newValue);
                }
            });
            c.graphicProperty().bind(Bindings.when(c.emptyProperty()).then((Node) null).otherwise(comboBox));
            return c;
        });
    

提交回复
热议问题