How to select and retrieve column with checkbox control with javafx


Question

In my Javafx2 application I have a TableView in which I want to have CheckBoxes to select one or many column.

I find many answer to make an entire column dedicated for checkbox by row, but in my case, i want to add a checkbox for each column label in order to select only the column checked when the user clic on a button for computate a row.

I see there is a javafx.scene.control.cell.CheckBoxTableCell<S,T> but i can i use it for tableview column selection ?

Is it possible ?

Update 1 :

Thanks to @amru, it's possible to add Node into header of TableColumn object. So i have another question, what is the best way to retrieve indexes of all selected column ? As far as I'm concerned, i search also in javafx api

1
3
10/30/2012 2:05:57 PM

Accepted Answer

This code will put a checkbox in the column header.

column.setGraphic(new CheckBox());

UPDATED: Set the checkbox's user data with the column. You can retrieve it later when user ticked the checkbox.

EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            CheckBox cb = (CheckBox) event.getSource();
            TableColumn column = (TableColumn) cb.getUserData();
            if (cb.isSelected()) {
                lstClm.add(column);
            } else {
                lstClm.remove(column);
            }
            for (TableColumn clm : lstClm) {
                System.out.println("selected column: " + clm.getText());
            }
        }
    };
    CheckBox cb = new CheckBox();
    cb.setUserData(firstDataColumn);
    cb.setOnAction(handler);
    firstDataColumn.setGraphic(cb);

    cb = new CheckBox();
    cb.setUserData(secondDataColumn);
    cb.setOnAction(handler);
    secondDataColumn.setGraphic(cb);
4
10/31/2012 1:22:40 AM

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