-3

I want to change how the all column's text looks like which is a SimpleStringProperty. I want to change font style,font name, font size etc... Below my creation of TableView

TableView<User> statisticsTable = new TableView<>();
        //statisticsTable.setPrefHeight(DefaultValues.TE);
        TableColumn nameCol = new TableColumn("Name");
        nameCol.setMinWidth(240);
        nameCol.setCellValueFactory(
                new PropertyValueFactory<User, String>("fullName"));
        nameCol.setResizable(false);

        TableColumn todayTicketsCol = new TableColumn("Today Assigned Tickets");
        todayTicketsCol.setMinWidth(160);
        todayTicketsCol.setCellValueFactory(
                new PropertyValueFactory<User, Integer>("totalOnTechnicalStudies"));
        todayTicketsCol.setResizable(false);

        TableColumn totalTechnicalStudiesCol = new TableColumn("Total Technical Studies");
        totalTechnicalStudiesCol.setMinWidth(160);
        totalTechnicalStudiesCol.setCellValueFactory(
                new PropertyValueFactory<User, Integer>("totalAssignedTicket"));
        totalTechnicalStudiesCol.setResizable(false);

        usersForStatistics = FXCollections.observableArrayList(usersList);
        statisticsTable.getColumns().addAll(nameCol,todayTicketsCol,totalTechnicalStudiesCol);
        statisticsTable.setItems(usersForStatistics);
1

2 Answers 2

4

Here is a sample app that demonstrates how to do this.

This example uses setTextFill() and setFont() inside the setCellFactory method.

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;


public class Main extends Application {

    private final TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(new Person("A", "B"));
    final HBox hb = new HBox();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setWidth(450);
        stage.setHeight(550);


        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<>("firstName"));
        //Newly added code
        firstNameCol.setCellFactory(new Callback<TableColumn, TableCell>() {

            @Override
            public TableCell call(TableColumn param) {
                return new TableCell<Person, String>() 
                {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);

                        if(isEmpty())
                        {
                            setText("");
                        }
                        else
                        {

                            setTextFill(Color.RED);
                            setFont(Font.font ("Verdana", 20));
                            setText(item);
                        }
                    }
                };
            }
        });



        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<>("lastName"));
        lastNameCol.setCellFactory(new Callback<TableColumn, TableCell>() {

            @Override
            public TableCell call(TableColumn param) 
            {
                return new TableCell<Person, String>() 
                {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);

                        if(isEmpty())
                        {
                            setText("");
                        }
                        else
                        {

                            setTextFill(Color.BLUE);
                            setFont(Font.font ("Verdana", 20));
                            setText(item);
                        }
                    }
                };
            }
        });

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

        final Button addButton = new Button("Add");
        addButton.setOnAction((ActionEvent e) -> {
            data.add(new Person("Z","X"));
         });

        hb.getChildren().addAll(addButton);
        hb.setSpacing(3);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(table, hb);

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

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
} 

enter image description here

2
  • Thanks for good and fast answer. Fixed lots of problems. Css approach can not style single cells. If it can then i am up for it. Jan 17, 2018 at 12:23
  • 1
    @MertSerimer I added a solution that uses CSS (basically the same concept as this answer, but moves the actual style to an external CSS file). Nothing wrong with the solution posted here, I just think it is preferable to factor the styles out into an external file (especially in larger projects).
    – James_D
    Jan 25, 2018 at 2:11
4

Sedrick's answer works perfectly well, and is a reasonable approach. I would just suggest a slight modification that allows separation of the style from the controller code using an external CSS file. The basic structure is the same, but instead of hard-coding the style in the cell implementation, simply set a style class on the cell, and then apply rules to that style class with CSS.

So the cell factory would look like

TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
        new PropertyValueFactory<>("firstName"));

// modified cell factory:
firstNameCol.setCellFactory(tc -> {

    TableCell<Person, String> cell =new TableCell<Person, String>() {
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? "" : item);
        }
    };

    // maybe choose a more suitable name here...
    cell.getStyleClass().add("first-name-col"); 
    return cell ;
});

Now attach an external css file to the scene (or some parent of the table) with the following:

.first-name-col.table-cell {
    -fx-font-family: verdana ;
    -fx-font-size: 20pt ;
    -fx-text-fill: red ;
}

As well as separating the styles into a CSS file, which can easily be modified and can be identified by a logical name describing the reason for the style being applied (i.e. not "first-name-col" as used here), this also makes it easier if you have many columns, perhaps with some styles being shared between them and some styles being unique. You can easily write a method that generates the table cell with one or more style classes attached, so pretty much all the code gets reused, and then different styles are applied to different classes in the CSS.

You can also use this technique if the style might vary among the cells in the same column: simply add and remove style classes (or set CSS PseudoClasses) in the updateItem(...) method.

So, e.g.:

TableColumn<Person, Integer> todayTicketsCol = new TableColumn<>("Today assigned tickets");
// ...
todayTicketsCol.setCellFactory(tc -> {
    TableCell<Person, Integer> cell = new TableCell<Person, Integer>() {
        private final PseudoClass critical = PseudoClass.getPseudoClass("critical");

        @Override
        protected void updateItem(Integer numTickets, boolean empty) {
            super.updateItem(numTickets, empty);
            if (empty) {
                setText("");
                pseudoClassStateChanged(critical, false);
            } else {
                setText(numTickets.toString());
                pseudoClassStateChanged(critical, numTickets.intValue() >= 50);
            }
        }
    };

    cell.getStyleClass().add("numeric");
    return cell ;
});

With CSS, for example, like

.numeric.table-cell {
    -fx-alignment: center-right ;
}
.numeric.table-cell:critical {
    -fx-text-fill: red ;
}
1
  • Thanks a lot. I switched to this. Jan 25, 2018 at 4:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.