PathTextField: quick example of property usage in JavaFX

Context

Properties and binding in JavaFX is a really interesting feature that sometimes is hard to illustrate. Recently I just faced a problem in CompilerFX: file paths entered by the user could be problematic. Indeed on some platforms path separator is \ and on others it is /. In Java you can often use / as path separator.

Practice

So in our example, you can choose many solutions like for example:

When the user submit the path in a text field, replace all \ by /;

When the user enter a \, use a key event to replace it;

Choose a more JavaFX way.

Let’s deal with the third solution. Have this ones in mind:

In JavaFX you have the properties, allowing you to listen for a change using a ChangeListener;

The text of a TextField is store in the text property.

You could implement the second solution listen previously but let’s work with a custom text field that will replace replace all \ by /.