Ordering via SortedList (and Properties Extractor)

Quite a while ago (almost 1,5 years 😱) I wrote a post about the JavaFX way to get ListViews and TableViews instantly updated on model data change: using Properties Extractor pattern.

TableColumns have a build-in support for sorting the data per column: just double-click the column header (. But how to order ListViews or get the table content get ordered by certain predicate instantly on data changes?

To sort elements the ObervableList has a sort(Comparator<? super E> c) method to sort the list according to the order induced by the specified Comparator (each time it is called).
Note: If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’ natural ordering should be used.

I have extended the demo app in terms of sorting:

SortedList and FilteredList

SortedList and FilteredList are very interesting and useful wrapper for OberservableLists to keep the content sorted and/or filtered (will add filtering soon).

SortedList: Wraps an ObservableList and sorts it’s content. All changes in the ObservableList are propagated immediately to the SortedList.

FilteredList: Wraps an ObservableList and filters it’s content using the provided Predicate. All changes in the ObservableList are propagated immediately to the FilteredList.

You can create a SortedList by creating it “manually”:

personSortedList = new SortedList(model.getPersonFXBeans());

or let the ObservableList do it for you:

personSortedList = model.getPersonFXBeans().sorted();

“Readonly TableView” and “ListView” are sharing the same SortedList wrapper:




The “Sorting” ComboBox contains the available comparators for the SortedList:

personComparators = FXCollections.observableArrayList(new FirstNameComparator(),
                new LastNameComparator(),
                new DateOfBirthComparator(),
                new AgeComparator(),
                new DaysToNextBirthdayComparator(),
                new NextBirthdayComparator()
public void onSortByComparator() {

Also there is a toggle for the sort direction:

public void onChangeSortDirection() {

The “Editable TableView” is still “self-sufficient” in terms of sorting.

All three views are sharing the same data model (model.getPersonFXBeans()) and editing the content is instantly notified by them (via property extractor).

If you play with the app by changing the data: note also the sorting take effect. 

One more thing

If you bind the comparatorProperty() of SortedList to the TableView, the sorting the content is triggered by the build-in ordering options ig TableView (via column header):


Note that other ways to trigger the SortedList e.g. by setCompartor() will fail then with exception as comparatorProperty is already bound.

How to allow users to customize the UI


Take advantage of the declarative design pattern of JavafX/FXML and allow users to customize a certain view without any coding just by opening it with e.g. SceneBuilder to re-arrange the layout or add new controls or even change the style according to the users needs.

The FXML file + CSS can be basically be placed whereever they are reachable via a URL.
The user must only know the interface/methods of the assigned controller class inside the FXML.


Assuming this simple demo controller class provides methods to remotely control devices and to send MQTT messages, a user is able to customize his own remote control.

public class RemoteController{

    public void onTest(){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
    public void onTest(String value){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
    public void onSwitch(String houseCode, int groudId, int deviceId, String command){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setContentText(String.format("Command: send %s %d %d %s", houseCode, groudId, deviceId, command));

remote.fxml and remote.css

Note the referenced de.jensd.shichimifx.demo.ext.RemoteController and remote.css.
So basically controller actions can be called via


If you add

<?language javascript?>

to FXML, it’s also possible to pass parameters by a JavaScript call via the controller-instance.


Unfortunately I can’t find more documentation about this feature than -> this, but somehow it magically it works ;-). Its even possible to pass different types of parameters.

<?xml version="1.0" encoding="UTF-8"?>

<?language javascript?>
<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<VBox alignment="TOP_CENTER" prefHeight="400.0" prefWidth="600.0" spacing="20.0" styleClass="main-pane" stylesheets="@remote.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.jensd.shichimifx.demo.ext.RemoteController">
      <Label styleClass="title-label" text="Universal Remote" />
      <HBox alignment="CENTER_RIGHT" spacing="20.0">
            <Label layoutX="228.0" layoutY="96.0" styleClass="sub-title-label" text="Light Frontdoor" />
            <Button layoutX="43.0" layoutY="86.0" mnemonicParsing="false" onAction="#onTest" prefWidth="150.0" styleClass="button-on" text="ON" />
            <Button layoutX="411.0" layoutY="86.0" mnemonicParsing="false" onAction="#onTest" prefWidth="150.0" styleClass="button-off" text="OFF" />
            <Insets left="10.0" right="10.0" />
      <HBox alignment="CENTER_RIGHT" spacing="20.0">
            <Label layoutX="228.0" layoutY="96.0" styleClass="sub-title-label" text="Light Garden" />
            <Button layoutX="43.0" layoutY="86.0" mnemonicParsing="false" onAction="controller.onTest('ON')" prefWidth="150.0" styleClass="button-on" text="ON" />
            <Button layoutX="411.0" layoutY="86.0" mnemonicParsing="false" onAction="controller.onTest('OFF')" prefWidth="150.0" styleClass="button-off" text="OFF" />
            <Insets left="10.0" right="10.0" />
      <HBox alignment="CENTER_RIGHT" spacing="20.0">
            <Label layoutX="228.0" layoutY="96.0" styleClass="sub-title-label" text="Light Garden" />
            <Button layoutX="43.0" layoutY="86.0" mnemonicParsing="false" onAction="controller.onSwitch('a', 1,1,'ON')" prefWidth="150.0" styleClass="button-on" text="ON" />
            <Button layoutX="411.0" layoutY="86.0" mnemonicParsing="false" onAction="controller.onTest('OFF')" prefWidth="150.0" styleClass="button-off" text="OFF" />
            <Insets left="10.0" right="10.0" />
      <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />

Based on this example a user is able to simple open the FXMl with SceneBuilder and to add new Button calling the controller.onSwitch() method to control different/new devices installed for home automation.

The next release of ShichimiFX will contain a new Utilily class to load FXML as shown in the ExternalFXMLDemoController. Note that the loaded Pane is added to the center of the externalPane (BorderPane) of the Demo-Application via onLoadExternalFxml():

public class ExternalFXMLDemoController {

    private ResourceBundle resources;

    private BorderPane externalPane;

    private TextField fxmlFileNameTextField;

    private Button chooseFxmlFileButton;

    private Button loadFxmlFileButton;

    private StringProperty fxmlFileName;

    public void initialize() {

    public StringProperty fxmlFileNameProperty() {
        if (fxmlFileName == null) {
            fxmlFileName = new SimpleStringProperty("");
        return fxmlFileName;

    public String getFxmlFileName() {
        return fxmlFileNameProperty().getValue();

    public void setFxmlFileName(String fxmlFileName) {

    public void chooseFxmlFile() {
        FileChooser chooser = new FileChooser();
        chooser.setTitle("Choose FXML file to load");
        if (getFxmlFileName().isEmpty()) {
            chooser.setInitialDirectory(new File(System.getProperty("user.home")));
        } else {
            chooser.setInitialDirectory(new File(getFxmlFileName()).getParentFile());

        File file = chooser.showOpenDialog(chooseFxmlFileButton.getScene().getWindow());
        if (file != null) {

    public void onLoadExternalFxml() {
        try {
            Optional<URL> url = FxmlUtils.getFxmlUrl(Paths.get(getFxmlFileName()));
            if (url.isPresent()) {
                Pane pane = FxmlUtils.loadFxmlPane(url.get(), resources);
            } else {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText(getFxmlFileName() + " could not be found!");
        } catch (IOException ex) {

Properties Extractor: Best way to get the ListView instantly updating its elements

This post is about how to deal with JavaFX ListViews and TableViews and how these controls are getting informed about changed content of the contained elements.
I wonder why I didn’t find anything about the following pattern in the relevant books as this is a really crucial mechanism.
Many posts out there suggest to force triggering a ChangeEvent getting a ListView to refresh by calling


after each commited change! Brrr ;-)!

But there is a much better way:
Enable your list to report changes on the element by providing an properties extractor.

The Demo App
I have created a small demo app to play with for giving it a try.
Basically two TableViews and one ListView all sharing the same data.
To change properties of the elements one TableView is editable:
PropertiesExtractor Demo1

The DataModel

The compulsive PersonBean folling the JavaFX Bean Pattern/Convention

public class PersonBean {

    private StringProperty firstName;
    private StringProperty lastName;
    private ObjectProperty<LocalDate> birthday;
    private ObjectBinding<Long> age;

    public PersonBean() {

    public PersonBean(String firstName, String lastName, LocalDate birthday) {

    public final StringProperty firstNameProperty() {
        if (firstName == null) {
            firstName = new SimpleStringProperty();
        return firstName;

    public final String getFirstName() {
        return firstNameProperty().get();

    public final void setFirstName(final java.lang.String firstName) {

    public final StringProperty lastNameProperty() {
        if (lastName == null) {
            lastName = new SimpleStringProperty();
        return lastName;

    public final java.lang.String getLastName() {
        return lastNameProperty().get();

    public final void setLastName(final java.lang.String lastName) {

    public final ObjectProperty<LocalDate> birthdayProperty() {
        if (birthday == null) {
            birthday = new SimpleObjectProperty<>();
        return birthday;

    public final LocalDate getBirthday() {
        return birthdayProperty().get();

    public final void setBirthday(final java.time.LocalDate birthday) {


    public String stringValue() {
        return String.format("%s %s %s", getFirstName(), getLastName(), getBirthday().format(DateTimeFormatter.ISO_LOCAL_DATE));

    public final ObjectBinding<Long> ageBinding() {
        if (age == null) {
            age = new ObjectBinding<Long>() {

                protected Long computeValue() {
                    if (getBirthday() == null) {
                        return null;
                    return getBirthday().until(LocalDate.now(), ChronoUnit.YEARS);
        return age;

    public static Callback<PersonBean, Observable&#91;&#93;> extractor() {
        return (PersonBean p) -> new Observable[]{p.lastNameProperty(), p.firstNameProperty(), p.birthdayProperty(), p.ageBinding()};

DataModel containing a List of randomly created PersonBeans:

public class DataModel {

    private ObservableList<PersonBean> personFXBeans;

    public DataModel() {

    private void init() {
        personFXBeans = DataSource.getRandomPersonBeansList(100);

    public ObservableList<PersonBean> getPersonFXBeans() {
        return personFXBeans;

As you may know to assign a DataModel e.g. to a TableView or a ListView in JavaFX you just have to use the setItems(ObvervableList) method.

public void onFillWithDemoDataFXBeans() {

Now getting a TableView informed about property changes of contained elements is already done you for by the binding either in two ways:
via a PropertyValueFactory and by more or less direct property binding:

readOnlyFirstNameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
readOnlyLastNameColumn.setCellValueFactory(new PropertyValueFactory<>("lastName"));
readOnlyBirthdayColumn.setCellValueFactory(new PropertyValueFactory<>("birthday"));
readOnlyAgeColumn.setCellValueFactory(i -> i.getValue().ageBinding());

editableFirstNameColumn.setCellValueFactory(i -> i.getValue().firstNameProperty());
editableLastNameColumn.setCellValueFactory(i -> i.getValue().lastNameProperty());
editableBirthdayColumn.setCellValueFactory(i -> i.getValue().birthdayProperty());
ageColumn.setCellValueFactory(i -> i.getValue().ageBinding());

But the ListView basically only observes the list and not the properties of each element of that list.

When using a ObservableList created by FXCollections.observableArrayList() the ListView will only refresh on ListChange Events like remove() an add() of elements. Therefore


after each commited change.

But there is a much better way:
Enable your list to report changes on the element by providing an properties extractor.
You don’t have to care about refreshing then!

ObservableList persons = FXCollections.observableArrayList(PersonBean.extractor());

See DataSource.getRandomPersonBeansList(int length):

public static ObservableList<PersonBean> getRandomPersonBeansList(int length) {
        ObservableList<PersonBean>  persons = FXCollections.observableArrayList(PersonBean.extractor());
        for (int i = 0; i < length; i++) {
            persons.add(new PersonBean(getRandomName(), getRandomLastname(), getRandomLocalDate()));
return persons;

This Extrator is basically a Callback containing an array of Obvervables which are then observed by the Obervablelist (more precicely: ObservableListWrapper):

My PersonBean already provides it’s extrator callback:

public static Callback<PersonBean, Observable[]> extractor() {
   return (PersonBean p) -> new Observable[]{p.lastNameProperty(), p.firstNameProperty(), p.birthdayProperty(), p.ageBinding()};

Following this pattern all controls are updated instantly after applying the change.

Edit data…
PropertiesExtractor Demo3

and commit:
PropertiesExtractor Demo4

You can find the complete code at my BitBucket Repo

ShichimiFX – Yet another JavaFX utils lib


ShichimiFX is a small lib containing helper/util classes extracted from my other projects which I commonly need. The lib will be extended if it turns out that I need a util class in more than one project…
(Shichimi is my favorite Japanese spice mixture)

And yes it also yet another utils lib containing (among others):

For further details refer to the ShichimiFX Bitbucket Repo




The JDK 8u20 “Tap trap”

When switching MQTT.fx to JDK 8u20 I was nicked by the fix of RT-24658.
The fix definitely makes sense but may clash with my TabPaneDetacher approach.

In MQTT.fx the content of the Tabs is disabled as long the MQTT-Broker is not connected.
And I am using Property Bindings for this. E.g. in the PublishController “publishBox” is the root of the Publish-Tab content and it is bound to the brokerConnectedProperty():


This worked well until JDK 8u20 as now this leads into:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: A bound value cannot be set.
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:139)
at javafx.scene.Node.setDisable(Node.java:1539)

This is because each time when e.g. adding a Tab to a TabPane updateDisabled() is called to explicitly SET the disabled value of the content also:

 private void updateDisabled() {
        boolean disabled = isDisable() || (getTabPane() != null && getTabPane().isDisabled());

        // Fix for RT-24658 - content should be disabled if the tab is disabled
        Node content = getContent();
        if (content != null) {

Options to deal with this:
Quit using Binding here and use ChangeListener instead.
Or simply wrap the content root in another Pane.

UI logic with using JavaFX Bindings

For MQTT.fx I needed a ComboBox to enter new Topics or to choose recent topics from list.
But I want the user to enter or choose only (more or less) reasonable values otherwise the “Publish”/”Subscribe” buttons should be disabled:

ComboBox Bindings Demo 1

ComboBox Bindings Demo 2

Using the JavaFX Bindings API prevents some boilerplate code (implementing Listeners) and it is even more flexible as the result can be bound to several controls and at the end of the day its much more readable.

Contraint 1: The selection must not be empty.

  1. First create a JavaFX BooleanBinding.
  2. Then bind it to the disabledProperty of the button.

Contraint 2: Entered values must not contain only blanks (leading/trailing blanks can be trimmed later).

My approach is to

  1. add an EventFilter and to consume the event in case of only entered character is “SPACE”
  2. and if there are just blanks left when editing the value the content is cleared.
public class ComboBoxBindingsDemoController {

    private Label valueLabel;

    private Button goButton;

    private ComboBox<String> valueComboBox;

    private ObservableList<String> demoItemsList;
    private static final Pattern LEADING_BLANKS_PATTERN = Pattern.compile("^\\s*+");

    public void initialize() {

        BooleanBinding goButtonState = valueComboBox.editorProperty().get().textProperty().isEmpty()


        valueComboBox.getEditor().addEventFilter(KeyEvent.KEY_TYPED, (KeyEvent event) -> {
            Matcher matcher = LEADING_BLANKS_PATTERN.matcher(valueComboBox.getEditor().getText());
            if (" ".equals(event.getCharacter()) && valueComboBox.getEditor().getText().length() == 0) {
            else if(matcher.matches()){


    public ObservableList<String> getDemoItemsList() {
        if (demoItemsList == null) {
            demoItemsList = FXCollections.observableArrayList();
        return demoItemsList;

    public void goAction() {
        System.out.println("Value '" + valueComboBox.getValue().trim() + "'");


Complete runnable demo can be found at Bitbucket.