Read selection from TableView in JavaFX 2.0


Question

I am trying to get the selection from a TableView in JavaFX 2.0. what happens is that I need to get the value of the row you selected in tableview I hope someone can help me

As would be placed on a table

I mean I want to get the data you select and if there is any way to handle an event to get the selected row automatically

1
10
11/15/2012 5:00:39 PM

Accepted Answer

you need ChangeListener and Clipboard to accomplish your task :)

Example Code :

Clipboard clipboard = Clipboard.getSystemClipboard(); 
  // add listner to your tableview selecteditemproperty   
userTable.getSelectionModel().selectedItemProperty().addListener( new ChangeListener() {
              // this method will be called whenever user selected row
            @override
             public void chnaged(ObservableValue observale, Object oldValue,Object newValue) {
               UserClass selectedUser = (UserClass)newValue;
             ClipboardContent content = new ClipboardContent();
                 // make sure you override toString in UserClass
             content.putString(selectedUser.toString()); 
             clipboard.setContent(content); 
            }
            });
9
11/16/2012 2:43:32 AM

If i understood you correctly, you want to retrieve the row number of the cell that is currently selected inside a TableView.

To do this, request the SelectionModel of the TableView:

    // tv is of type TableView
    TableView.TableViewSelectionModel selectionModel = tv.getSelectionModel();
    ObservableList selectedCells = selectionModel.getSelectedCells();
    TablePosition tablePosition = (TablePosition) selectedCells.get(0);
    int row = tablePosition.getRow(); // yields the row that the currently selected cell is in

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