lunes, 15 de mayo de 2017

FXTableViewUtil: An utility class for JavaFX to create columns easily in a TableView

I had to move a desktop application in VB6 because the customer needed to run their app in Windows, Mac and Linux so, we decided to use Java with JavaFX. SceneBuilder help me a lot to build user interfaces. Most of the screens are only tho show information in a TableView component.

Usually to create columns in a TableView you have to code something like this:

    private TableView table;

    public static void main(String[] args) {

    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));


        // Create Columns
        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));

        TableColumn emailCol = new TableColumn("Email");
        emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));

        // add columns to TableView
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);

As you can see you have to write several lines of code to add columns.

I wrote an utility class to create columns easly in a TableView, so now you only need to write something like this:

    public void initialize(URL url, ResourceBundle rb) {
        tableViewUtil.createColumns(Person.class, tableView, headers, personList);

FXTableViewUtil has this methods


Creates columns at runtime, you only need to add a TableView with no columns in your FXML file and pass the POJO class to be used and the object list to populate the TableView.  Columns added have a default width.

Check that this screen has a TableView without columns

TableView with no columns
Once you call method createColumns columns are added to TableView (using same with for all columns)
TableView after call createColumns method


Use this method if you already designed you TableView with columns. The important this to use this method is to assign the property name to Id in FXML file.

This screen already have TableColumns with custom with for each column (and different order)

TableView with columns at design time

Once you call method assignColumns FXTableViewUtil uses current design and assign the data to corresponding columns
TableView with data after call assignColumns

You can download project from Github at

No hay comentarios:

Publicar un comentario