'freeze first column in tableview javafx

I have a tableview(javafx) where I want to freeze the first column, means if you scroll to the right side, the first column would always remain in place on screen. How can I do that? All I have just a basic code to fill data in tableview.

javafx.scene.control.TableColumn[] tableColumn = new javafx.scene.control.TableColumn[columnHeaderNamesArray.length];

    // add columns
    List<String> columnNames = Arrays.asList(columnHeaderNamesArray);
    for (int i = 0; i < columnNames.size(); i++)
    {
        final int finalIdx = i;
        javafx.scene.control.TableColumn<ObservableList<String>, String> column = new javafx.scene.control.TableColumn<>(columnNames.get(i));
        column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(String.valueOf(param.getValue().get(finalIdx))));
        tableColumn[finalIdx] = column;
    }

    mTableFxPanel = new JFXPanel();
    add(mTableFxPanel);
    mTableFxPanel.setVisible(true);
    tableView = new TableView<ObservableList<Object>>();

    tableView.setEditable(true);
    for (int i = 0; i < dataMatrix.length; i++)
        tableView.getItems().add(FXCollections.observableArrayList(Arrays.asList(dataMatrix[i])));

    tableView.getColumns().addAll(tableColumn);
    tableView.getSelectionModel().setCellSelectionEnabled(true);

    ((Group) scene.getRoot()).getChildren().addAll(tableView);


Solution 1:[1]

Code worked with javafx 11

import javafx.application.Platform;
import javafx.scene.AccessibleAttribute;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TableCell;
import javafx.scene.layout.Region;

public class LockedTableCell<T, S> extends TableCell<T, S> {
        
    {

        Platform.runLater(() -> {

            try {
                ScrollBar scrollBar = (ScrollBar) getTableView()
                            .queryAccessibleAttribute(AccessibleAttribute.HORIZONTAL_SCROLLBAR);
                // set fx:id of TableColumn and get region of column header by #id
                Region headerNode = (Region) getTableView().lookup("#" + getTableColumn().getId());
                scrollBar.valueProperty().addListener((ob, o, n) -> {
                    double doubleValue = n.doubleValue();
                    
                    // move header and cell with translateX & bring it front
                    headerNode.setTranslateX(doubleValue);
                    headerNode.toFront();

                    this.setTranslateX(doubleValue);
                    this.toFront();

                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        });

    }

}

Using it:

tableColumnInstance.setCellFactory(param -> new LockedTableCell<>() {...});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NamLH