JavaFX
JavaFX snippets: periodic actions, FXML controller lifecycle, user-agent stylesheets, high-contrast themes, the virtual keyboard and pie chart labels.
4 min readUpdated
JavaFX is the Java UI toolkit for desktop and embedded applications. Since Java 11 it ships separately as OpenJFX. This note collects small recipes: running a task on a timer, the order in which an FXML controller is set up, switching the built-in theme, enabling high-contrast themes and the on-screen keyboard, and showing values in pie chart labels.
Run a periodic action
A Timeline with one KeyFrame and an indefinite cycle count runs an action at a fixed interval on the JavaFX Application Thread, so the handler may update the UI directly.
Timeline timeline = new Timeline( new KeyFrame( Duration.millis(2500), ae -> System.out.println("Periodic action") ));timeline.setCycleCount(Animation.INDEFINITE);timeline.play();Call timeline.stop() to end it.
Use initialize, not the constructor, in an FXML controller
FXMLLoader first calls the controller’s constructor, then injects the @FXML fields, then calls initialize(). The constructor therefore cannot use fields that refer to components defined in the .fxml file; initialize() can.
public class MyController implements Initializable { @FXML TableView<MyModel> tableView;
public MyController() { tableView.getItems().addAll(getDataFromSource()); // NullPointerException: tableView is still null here }
@Override public void initialize(URL url, ResourceBundle rb) { tableView.getItems().addAll(getDataFromSource()); // works: FXMLLoader has injected all @FXML fields }}Implementing Initializable is optional: a no-argument method @FXML public void initialize() is called the same way.
Set the user-agent stylesheet
The user-agent stylesheet is the built-in theme. Caspian was the default in JavaFX 2.x; set it on a scene with:
scene.setUserAgentStylesheet(Application.STYLESHEET_CASPIAN);Modena has been the default since JavaFX 8:
scene.setUserAgentStylesheet(Application.STYLESHEET_MODENA);To change the theme for the whole application instead of one scene, call the static Application.setUserAgentStylesheet(...) with the same constants.
Enable a high-contrast theme
Modena has high-contrast variants. Select one with a system property on the command line:
-Dcom.sun.javafx.highContrastTheme=yellowOnBlackThe valid values are yellowOnBlack, whiteOnBlack and blackOnWhite.
Enable the virtual keyboard
The on-screen keyboard is turned on with three system properties. They are JVM options, so they go before -jar (or the main class), not after it as application arguments.
-Dcom.sun.javafx.isEmbedded=true-Dcom.sun.javafx.touch=true-Dcom.sun.javafx.virtualKeyboard=javafxThe CSS rules that style the keyboard are in /com/sun/javafx/scene/control/skin/caspian/fxvk.css. With the JavaFX bundled in Java 8, that file is inside jre/lib/ext/jfxrt.jar; copy its selectors into your own stylesheet to customise the layout.
In a NetBeans Maven project, put the options in the run action in nbactions.xml:
<runfx.args>-jar -Dcom.sun.javafx.isEmbedded=true -Dcom.sun.javafx.touch=true -Dcom.sun.javafx.virtualKeyboard=javafx ${project.build.directory}/${project.build.finalName}.jar</runfx.args>Note: FXVK (com.sun.javafx.scene.control.skin.FXVK) is an internal, unsupported class. On modular JavaFX (9 and later) the snippets below compile and run only when the package is exported to your code, for example with --add-exports javafx.controls/com.sun.javafx.scene.control.skin=ALL-UNNAMED at compile time and at run time.
Choose the keyboard type for a text field
Set the keyboard type as a property of the control. The keyboard then opens with that layout when the field gets focus.
TextField textField = new TextField();textField.getProperties().put(FXVK.VK_TYPE_PROP_KEY, "numeric");VK_TYPE_PROP_KEY accepts only text, numeric, url and email.
Show and hide the keyboard from a focus listener
To control the keyboard yourself, attach and detach it when focus changes:
textField.focusedProperty().addListener((ObservableValue<? extends Boolean> obs, Boolean oldValue, Boolean newValue) -> { VirtualKeyboard keyboard = new VirtualKeyboard(); if (newValue) { keyboard.show(textField); } else { keyboard.hide(); }});
public class VirtualKeyboard { public void show(TextField textField) { textField.getProperties().put(FXVK.VK_TYPE_PROP_KEY, "numeric"); FXVK.init(textField); FXVK.attach(textField); }
public void hide() { FXVK.detach(); }}Keep the keyboard closed for a field
To stop the keyboard from opening for one field, detach it as soon as the field gains focus:
textField.focusedProperty().addListener((obs, oldValue, newValue) -> { if (newValue) { FXVK.detach(); }});Show values in pie chart labels
By default a PieChart label shows only the data name. The simplest way to add the value is to bind each name to a string that includes it:
pieChartData.forEach(data -> data.nameProperty().bind( Bindings.concat(data.getName(), " ", data.pieValueProperty(), " Tons") ));To show percentages, keep the total in a DoubleBinding so it is recomputed only when the data changes, not on every access:
DoubleBinding total = Bindings.createDoubleBinding( () -> pieChartData.stream().collect(Collectors.summingDouble(PieChart.Data::getPieValue)), pieChartData);Binding the name also changes the legend. If the values change often, or the legend should show only the names, rewrite the label text during layout instead:
chart = new PieChart(pieChartData) { @Override protected void layoutChartChildren(double top, double left, double contentWidth, double contentHeight) { if (getLabelsVisible()) { getData().forEach(d -> { Optional<Node> textNode = lookupAll(".chart-pie-label").stream() .filter(n -> n instanceof Text && ((Text) n).getText().contains(d.getName())) .findAny(); textNode.ifPresent(n -> ((Text) n).setText(d.getName() + " " + d.getPieValue() + " Tons")); }); } super.layoutChartChildren(top, left, contentWidth, contentHeight); }};The override calls lookupAll on the chart itself rather than on the chart variable, which is not yet assigned when the first layout pass runs.