In my Java Desktop Application I have a TableView in which I want to have a column with CheckBoxes.
I did find where this has been done http://www.jonathangiles.net/javafx/2.0/CellFactories/ but as the download is not available and because I don't know how soon Jonathan Giles will answer my email I thought I'd ask...
How do I put a CheckBox in a cell of my TableView?
Uses
javafx.scene.control.cell.CheckBoxTableCell<S,T>
and the work's done !UPDATE: same code using Java 8 lambda expressions
Lines count is divided by two! (16 ==> 8)
UPDATE: same code using Java 10 "var" contextual word
EDIT to add full functional editable example (Java 8)
EDIT to add full functional editable example (Java 10)
The simplest solution is probably to do it in FXML:
First create the class below:
Then include a cell factory in your FXML:
You also need to add an import in the FXML, such as
<?import com.assylias.factories.*?>
Bonus: you can make the factory more customisable, for example to determine where the checkbox should appear, by adding fields to the
CheckBoxCellFactory
class, such as:And the FXML:
This is the way is do it
cb.setFocusTraversable(false) is necesary to prevent focus getting stuck on it.
setGraphic(null) is necesary to erase anything left behind after deleting an item or whenever the source list changes
Heres another one with a ToggleGroup and ToggleButtons
I did some test and memory consumption is basically the same as using a ComboBoxTableCell
This is how my little application looks (sry, my main language is Spanish and i build it for personal use)
for me, works with this solution:
and the tableCell:
if you dont need to make the checkbox with edit event
There is a very simple way of doing this, you don't need to modify your model class with SimpleBooleanProperty or whatever, just follow these steps:
1 - Suppose you have a "Person" object with a isUnemployed method:
2 - Create the callback class
3 - Bind the callback to the table column
If you use FXML, put the callback class inside your column:
Don't forget to import the class in your FXML:
Without FXML, do it like this:
4 - That's it
Everything should work as expected, with the value being set to the backing bean when you click on the checkbox, and the checkbox value correctly being set when you load the items list in your table.
Inspired from the previous answers, this is the shortest possible version, I think.