如何获取在 Table 视图中的 ComboBoxTableCell 中选择的值

How to get values selected in ComboBoxTableCell in Table View

我已经尝试使用此代码来获取组合框中选择的值并且此代码有效。

String cate = category.getValue().toString();

但是如何在 TableView 中的 ComboBoxTableCell 中获取选定的值?

使用下面的代码,我在 Table 视图中得到一个 ComboBox

columnmain2.setCellFactory(ComboBoxTableCell.forTableColumn(names.toString()));

以及如何在组合框 table 单元格的 Table 视图中获取选定的值?

当用户退出该组合框 table 单元格的编辑模式时,您可以获得组合框选择的值。即何时提交新值。您需要使用 tablecolumn.setOnEditCommit() 方法。这是一个完整的可运行示例代码(用于 ComboBoxTableCell 演示的 MCVE):

public class ComboBoxTableCellDemo extends Application
{
    private TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data
            = FXCollections.observableArrayList(
                    new Person( "Bishkek" ),
                    new Person( "Osh" ),
                    new Person( "New York" ),
                    new Person( "Madrid" )
            );

    @Override
    public void start( Stage stage )
    {
        TableColumn<Person, String> cityCol = new TableColumn<>( "City" );
        cityCol.setMinWidth( 200 );
        cityCol.setCellValueFactory( new PropertyValueFactory<>( "city" ) );
        cityCol.setCellFactory( ComboBoxTableCell.<Person, String>forTableColumn( "Bishkek", "Osh", "New York", "Madrid" ) );
        cityCol.setOnEditCommit( ( TableColumn.CellEditEvent<Person, String> e ) ->
        {
            // new value coming from combobox
            String newValue = e.getNewValue();

            // index of editing person in the tableview
            int index = e.getTablePosition().getRow();

            // person currently being edited
            Person person = ( Person ) e.getTableView().getItems().get( index );

            // Now you have all necessary info, decide where to set new value 
            // to the person or not.
            if ( ok_to_go )
            {
                person.setCity( newValue );
            }
        } );

        table.setItems( data );
        table.getColumns().addAll( cityCol );
        table.setEditable( true );

        stage.setScene( new Scene( new VBox( table ) ) );
        stage.show();
    }


    public static class Person
    {
        private String city;

        private Person( String city )
        {
            this.city = city;
        }


        public String getCity()
        {
            return city;
        }


        public void setCity( String city )
        {
            System.out.println( "city set to new value = " + city );
            this.city = city;
        }
    }


    public static void main( String[] args )
    {
        launch( args );
    }

}