Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javafx tableview how to get the row I clicked?

Tags:

javafx

here is my code

// this event is attached to TableCell
public EventHandler dblclickDescription = new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        if(event.getButton().equals(MouseButton.PRIMARY)){
            if(event.getClickCount() == 2){
                printRow(event.getTarget());
            }
        }
        event.consume();
    }
};

// print row
public void printRow(Object o){
    Text text = (Text) o;

    // ??? don't know what to write here

   System.out.println(row.toString());
}

1) how do I get from the cell I clicked to the row?

2) can I attach the event to the whole row instead of each column?

EDIT: 3) I thought that I attached the event on TableCell

TableCell cell = TableColumn.DEFAULT_CELL_FACTORY.call(p);
cell.setOnMouseClicked(dblclickDescription);

but when I tested,

event.getSource();// is a TableColumn
event.getTarget();// is a Text if clicked on text
event.getTarget();// is a TableColumn if clicked on empty space, even if that cell has text

is there a way to get TableCell from MouseEvent?

like image 277
hanbin615 Avatar asked May 12 '15 12:05

hanbin615


2 Answers

To get back the index of the row or the selected item, use this code :

Object object =  table.getSelectionModel().selectedItemProperty().get();
int index = table.getSelectionModel().selectedIndexProperty().get();

Then you can add a listener when the index / object change like this :

table.getSelectionModel().selectedIndexProperty().addListener((num) -> function());
like image 120
Thomas Avatar answered Oct 31 '22 23:10

Thomas


To answer your specific questions:

how do I get from the cell I clicked to the row?

TableCell defines a getTableRow() method, returning the TableRow. So you can do

Object item = cell.getTableRow().getItem();

which will give you the row item from the table (i.e. the correct element of table.getItems()). You can also get this from table.getItems().get(cell.getIndex()) if you prefer.

can I attach the event to the whole row instead of each column?

Yes. Define a rowFactory:

TableView<MyDataType> table = new TableView<>();

table.setRowFactory(tv -> {
    TableRow<MyDataType> row = new TableRow<>();
    row.setOnMouseClicked(event -> {
        if (! row.isEmpty() && event.getButton()==MouseButton.PRIMARY 
             && event.getClickCount() == 2) {

            MyDataType clickedRow = row.getItem();
            printRow(clickedRow);
        }
    });
    return row ;
});

// ...

private void printRow(MyDataType item) {
    // ...
}
like image 30
James_D Avatar answered Nov 01 '22 01:11

James_D