Skip to content
Advertisement

How to listen for clicks on dynamically generated buttons in TableCell?

I have a class Task that takes field values from the database and is displayed as a row in the table.

JavaScript

There is a controller that fills the rows of the table with objects of the Task class.

JavaScript

I need to listen for clicks on buttons in cells. But those buttons are not present as fields in the controller. How can I do this without referring to a specific cell?

Advertisement

Answer

Your model class Task should not have any Ui components in it. It should look something like

JavaScript

You should strongly consider implementing the model class with JavaFX Properties instead of implementing it as a plain Java bean.

To display UI controls in cells in the table, you should implement a custom TableCell and generate instances of it in a cell factory. Probably the most convenient approach is to let the column containing those cells have the entire model as its value. That way the cell’s getItem() method will return the model for its specific row.

JavaScript

And the cell implementation (here this is an inner class in the controller) looks like

JavaScript

Another approach would be to just let the cell values be null (e.g. using TableColumn<Task, Void> editColumn, etc.), and to access the row value in the cell with getTableView().getItems().get(getIndex()), but that seems less elegant.


Here is a complete working example, using the Task class I defined above.

Table.fxml

JavaScript

TableController.java

JavaScript

Application class:

JavaScript

Application running:

enter image description here

After pressing lots of “Remove” buttons:

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement