Error assigning a boolean value in a custom class extends from TextField (FXML)

Viewed 85

I started learning JavaFX and ran into this problem: I have a TextBox class extendsfrom TextField

package sample;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public class TextBox extends TextField {

    private int maxLength = 255;
    private boolean onlyDigits;

    public TextBox(){
        super();
    }

    @Override
    public void replaceText(int start, int end, String text) {
        String oldText = getText();
        super.replaceText(start, end, text);

        if (!verify()){
            setText(oldText);
        }
    }

    @Override
    public void replaceSelection(String text) {
        String oldText = getText();
        super.replaceSelection(text);

        if (!verify()){
            setText(oldText);
        }
    }

    private boolean verify() {
        String text = getText();

        if (text =="")
            return true;

        if (text.length() > maxLength) {
            return false;
        }
        if (onlyDigits && !Converter.StringToInt(text).isSuccess()){
            return false;
        }

        return true;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public void setMaxLength(int maxLength) {
        if (maxLength >= 0)
            this.maxLength = maxLength;
    }

    public void setOnlyDigits(boolean onlyDigits) {
        this.onlyDigits = onlyDigits;
    }

    public boolean isOnlyDigits() {
        return onlyDigits;
    }
}

When using the following FXML, I get an error:

<TextBox
                GridPane.columnIndex="0" GridPane.rowIndex="1"
                maxLength="2"
                onlyDigits="true"
                fx:id="tbNumberVertex" />

Caused by: javafx.fxml.LoadException: Error resolving onlyDigits='true', either the event handler is not in the Namespace or there is an error in the script.

But in case of maxLength everything works

1 Answers

I think that what is happening here is that, because the property onlyDigits begins with the text "on", the FXML parser is assuming it's an event handler property. (Like, for example, onAction.) So it's assuming the value assigned, true, refers to a function defined in a script in the FXML.

(For what it's worth, I'd consider this to be a bug.)

Change the name of the property, e.g. to useOnlyDigits by changing the names of the methods:

public void setUseOnlyDigits(boolean onlyDigits) {
    this.onlyDigits = onlyDigits;
}

public boolean isUseOnlyDigits() {
    return onlyDigits;
}

and update the FXML accordingly:

<TextBox
    GridPane.columnIndex="0" GridPane.rowIndex="1"
    maxLength="2"
    useOnlyDigits="true"
    fx:id="tbNumberVertex" />
Related