JavaFX TableView parent column label not visible

Viewed 561

I'm facing a problem when getting a snapshot of JavaFX TableView. I want to generate an image file of table without showing the stage. Everything works fine except the parent column labels disappear when the stage is not shown.

I have regular table with sample Person( name, age, email->(primary, secondary) ) data:

TableView<Person> personTable = new TableView<>();

TableColumn<Person, String> nameColumn = new TableColumn<>( "Name" );
TableColumn<Person, Integer> ageColumn = new TableColumn<>( "Age" );

TableColumn<Person, String> emailColumn = new TableColumn<>( "Email" );
TableColumn<Person, String> primaryEmailColumn = new TableColumn<>( "Primary" );
TableColumn<Person, String> secondaryEmailColumn = new TableColumn<>( "Secondary" );

nameColumn.setCellValueFactory( cellDataFeatures -> cellDataFeatures.getValue().nameProperty() );
ageColumn.setCellValueFactory( cellDataFeatures -> cellDataFeatures.getValue().ageProperty().asObject() );
primaryEmailColumn.setCellValueFactory( cellDataFeatures -> cellDataFeatures.getValue().primaryEmailProperty() );
secondaryEmailColumn.setCellValueFactory( cellDataFeatures -> cellDataFeatures.getValue().secondaryEmailProperty() );

emailColumn.getColumns().addAll( primaryEmailColumn, secondaryEmailColumn );
personTable.getColumns().addAll( nameColumn, ageColumn, emailColumn );

personTable.setItems( generatePersonList() );

Generating image file:

Scene scene = new Scene( personTable );
saveAsPng( personTable, "test2.png" );

Generated image(1)

As you can see the email's column label("Email") is not visible.

I can hack around this by showing the stage, taking the image and hiding the stage:

Scene scene = new Scene( personTable );
stage.setScene( scene );
stage.show();
saveAsPng( personTable, "test2.png" );
stage.close();

Generated image(2)

My aim is to generate second image(with "Email" label) without showing the stage.

I assumed that only the columns that have values associated with them have the graphics shown, so I tried the following, but to no avail:

emailColumn.setGraphic( new Label( "Test" ) );
emailColumn.setVisible( true );
emailColumn.getGraphic().setVisible( true );

saveAsPNG:

private void saveAsPng(Parent container, String path)
{
    File file = new File(path);
    WritableImage img = container.snapshot( null, null );
    RenderedImage renderedImage = SwingFXUtils.fromFXImage(img, null);
    try {
        ImageIO.write(renderedImage,"png", file);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Thanks!

1 Answers
Related