Sunday, June 8, 2014

JavaFX TableView with image background in header

I got to wondering how to set the background of a table to an image of some sort. It is pretty straight-forward with CSS. The only trick, really, is setting the background-color of the filler and column-header so the image can be seen. I used a semi-transparent white so the label text is easier to see.

.table-view > .column-header-background {
    -fx-background-image: url("https://duke.kenai.com/models/Duke3DprogressionSmall.jpg");
    -fx-background-size: stretch;
    -my-wash: rgba(255,255,255,.75);
}

.table-view > .column-header-background > .filler {
    -fx-background-color: -my-wash;
}

.table-view > .column-header-background > .nested-column-header > .column-header.table-column {
    -fx-background-color: -my-wash;

}

Sample code to try it on.

    static class Person {
        final StringProperty lastName  = new SimpleStringProperty();
        final StringProperty firstName  = new SimpleStringProperty();
        Person(String lastName, String firstName) {
            this.lastName.set(lastName);
            this.firstName.set(firstName);
        }
        StringProperty lastNameProperty() { return lastName; }
        StringProperty firstNameProperty() { return firstName; }
    }

    @Override
    public void start(Stage stage) throws Exception {

        TableColumn lastName = new TableColumn<>("Last");
        lastName.setCellValueFactory((value) -> value.getValue().lastNameProperty());

        TableColumn firstName = new TableColumn<>("First");
        firstName.setCellValueFactory((value) -> value.getValue().firstNameProperty());

        TableView tableView = new TableView();
        tableView.getColumns().setAll(lastName, firstName);
        tableView.getItems().setAll(
                new Person("Cratchit", "Bob"),
                new Person("Scrooge", "Ebenezer")
        );

        Group root = new Group(tableView);

        Scene scene = new Scene(root, 300, 500);
        scene.getStylesheets().add("/fxtest/test.css");
        stage.setScene(scene);
        stage.show();

    }

No comments:

Post a Comment