How to get values selected in ComboBoxTableCell in

2019-05-28 21:33发布

问题:

I have tried this code to get values selected in a combo box and this code works.

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

But how to get selected values in a ComboBoxTableCell inside TableView?

Using below code i am getting a ComboBox inside Table view

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

and how to get the values selected inside a Table view in combo box table cell?

回答1:

You can get the combobox selected value, when the user exits edit mode for that combobox table cell. Namely when the new value is committed. You need to use tablecolumn.setOnEditCommit() method. Here is a full runnable sample code (MCVE for ComboBoxTableCell Demo):

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

}