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
?
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());
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) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With