Using custom Controls in fxml

假装没事ソ 提交于 2019-12-05 12:50:33

Is this what you were looking for? This works fine for me.

package numerictextfield;

import java.util.regex.Pattern;

import javafx.scene.control.IndexRange;
import javafx.scene.control.TextField;

public class NumericTextField extends TextField {

    private final Pattern intPattern = Pattern.compile("[0-9]*");

    public NumericTextField(String text) {
        super(text);
    }
    public NumericTextField() {
        super();
        this.insertText(0, "");
        this.replaceSelection("");
        this.replaceText(new IndexRange(0, 0), "");
        this.replaceText(0, 0, "");
    }

    @Override
    public void insertText(int index, String text) {
        if (intPattern.matcher(text).matches()) {
            super.insertText(0, text);
        }
    }

    @Override
    public void replaceSelection(String text) {
        if (intPattern.matcher(text).matches()) {
            super.replaceSelection(text);
        }
    }

    @Override
    public void replaceText(IndexRange range, String text) {
        if (intPattern.matcher(text).matches()) {
            super.replaceText(range, text);
        }
    }

    @Override
    public void replaceText(int start, int end, String text) {
        if (intPattern.matcher(text).matches()) {
            super.replaceText(start, end, text);
        }
    }

}

and then

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

<?import javafx.scene.layout.AnchorPane?>
<?import numerictextfield.NumericTextField?>

<AnchorPane xmlns:fx="http://javafx.com/fxml" >
    <NumericTextField text="12345" >
        <AnchorPane.rightAnchor>65.0</AnchorPane.rightAnchor>
    </NumericTextField>
</AnchorPane>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!