Getting selected item from a JavaFX TableView


Question

How do I get the selected item from a TableView in JavaFX?

I am currently using

ObservableList selectedItems = taview.getSelectionModel().getSelectedItems();

but that does not return me the one selected item in the selection model.

1
30
4/1/2016 10:53:57 AM

Accepted Answer

Ok, lets say you have a data model class named Person. This way:

Person person = taview.getSelectionModel().getSelectedItem();
System.out.println(person.getName());    

Note that TableView must take a Person as a type argument to avoid casting:

@FXML
private TableView<Person> taview;

or

TableView<Person> taview = new TableView<>();

when your row is selected, you will return one Person instance. Then do what ever you want with that instance.

78
3/13/2015 5:22:21 PM

    tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
    @Override
    public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
        //Check whether item is selected and set value of selected item to Label
        if(tableview.getSelectionModel().getSelectedItem() != null) 
        {    
           TableViewSelectionModel selectionModel = tableview.getSelectionModel();
           ObservableList selectedCells = selectionModel.getSelectedCells();
           TablePosition tablePosition = (TablePosition) selectedCells.get(0);
           Object val = tablePosition.getTableColumn().getCellData(newValue);
           System.out.println("Selected Value" + val);
         }
         }
     });

Using this code you can get the selected value from JAVAFX TABLEVIEW Cell.

Thanks..


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon