1

I am trying to create a number field from text field in Javafx and reuse it in other fxml pages using scenebuilder.

MyNumberField.java

public class MyNumberField extends TextField {

public MyNumberField() {
    super();
    textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*")) {
                setText(newValue.replaceAll("[^\\d]", ""));
            }
        }
    });
}

}

I am able to do this in java but by creating a new object like below.

Anyfile.java ... MyNumberField txtNmbr = new MyNumberField(); ...

What I need is to use it in scenebuilder for creating the UI and then map it to my java file using @FXML MyNumberField numberField;

Tried the below steps:

  1. Tried changing tag to in FXML. But it gives an yellow exclamation and on refreshes fxml, it changes back to .

  2. Created MyNumberField.fxml and imported it to scenebuilder. MyNumberField.fxml

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

<?import javafx.scene.control.TextField?>


<TextField xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="<mypackage>.components.MyNumberField" />

Tried the way explained in a solution

But scene builder considers the imported MyNumberField.fxml as TextField and throws error if I try to do @FXML private MyNumberField txtNmbr; Custom Component in Scene Builder Error as below: Caused by: java.lang.IllegalArgumentException: Can not set .components.MyNumberField field .controller.LoginController.txtNmbr to javafx.scene.control.TextField

Can someone please help me on this?

Versions: openjdk-17.0.2_windows-x64_bin, openjfx-17.0.6_windows-x64_bin-sdk, JavaFX Scene Builder 8.5.0

adk
  • 11
  • 4
  • 2
    Slightly off-topic, but this is completely the wrong way to make a numeric text field. You should not change the value of a property (`text`) in a listener for the same property. Use a `TextFormatter` instead. – James_D Apr 11 '23 at 16:37
  • make sure that the JavaFX version you are using for your project matches the JavaFX version used by Scene Builder. JavaFX Scene Builder 8.5.0 uses JavaFX 8, but your project uses JavaFX 17. To use JavaFX 17 with Scene Builder, you can download Gluon Scene Builder 16.0.0 (which supports JavaFX 11 and later) or another compatible version. Note that the version number of Scene Builder does not directly correspond to the version of JavaFX it supports. – LSDeva Apr 11 '23 at 16:42

0 Answers0