Set font in javafx

javafx

Solution

Changing the table column style:

You should to use TableColumn#setCellFactory() to customize cell item rendering. For example, datamodel with like this Person class:

// init code vs..
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setCellFactory(getCustomCellFactory("green"));

TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setCellFactory(getCustomCellFactory("red"));

table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);

// scene create code vs..

and the common `getCustomCellFactory()` method:

private Callback<TableColumn<Person, String>, TableCell<Person, String>> getCustomCellFactory(final String color) {
        return new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {

            @Override
            public TableCell<Person, String> call(TableColumn<Person, String> param) {
                TableCell<Person, String> cell = new TableCell<Person, String>() {

                    @Override
                    public void updateItem(final String item, boolean empty) {
                        if (item != null) {
                            setText(item);
                            setStyle("-fx-text-fill: " + color + ";");
                        }
                    }
                };
                return cell;
            }
        };
    }

Changing the table column header style:

`TableView` like other controls of JavaFX uses a built-in style sheet named `caspian.css` which is bundled with jfxrt.jar. See the answer of "JavaFX 2 and CSS classes". To change the column font style you can either override the default style or customize it: Overriding:

.table-view .column-header{
    -fx-text-fill: -fx-selection-bar-text;
    -fx-font-size: 16;
    -fx-font-family: "Arial";
}

Customizing:

#my-custom .table-view .column-header {
    -fx-text-fill: red;
    -fx-font-size: 26;
    -fx-font-family: "Arial";
}

Overriding effects all `TableView`s in app. So if you prefer to customize then once you define multiple styles, you can apply the custom style to any tableview at runtime as,

myTableView.setId("my-custom");
...
// Apply another style at runtime
myTableView.setId("my-custom2");

To see how to define and load style sheet files to app, check out the post of "JavaFX How to set scene background image".

However, applying different styles to different columns requires more effort I think.

Problem

How to set font to a column in table view in java fx. I have a table with 3 columns and i want to set different fonts for each of the columns. Also, is it possible to change the font in runtime. Please help with some sample code.

Original source

Related problems