在fxml中使用自定义控件

 2023-02-16    344  

问题描述

假设我已经划分了Javafx提供的默认TableView<T>类,并创建了一个类PersonTableView extends TableView<Person>.该子类存在于Java代码中,根本不使用FXML.它定义并封装了我为Person对象专门需要的行为.

现在,我想在FXML文件中使用我的自定义类的实例,就像我使用所有默认控件一样.那正是我的问题,我不知道我该怎么做,或者这是否是一个好/普遍的设计决定.

在fxml中使用自定义控件

我想在自己的类中封装我的特定表观视图的行为,但是应该在FXML中定义布局,因为它与逻辑无关,它只是化妆品.

我想象一种语法和功能,例如在.NET的WPF中可以找到它,您可以像其他任何控件一样在标记中使用自定义类,因为XAML和C#比Java和fxml更紧密地耦合.

从我当前的角度来看,我所描述的是无法做到的,而我最终只会使用很少的FXML和更多的代码,即使是仅适用于布局的零件.例如,我不想使用这样的代码:

AnchorPane.setRightAnchor(customControl, 65.0);

因为我相信将其定义为我的FXML是个好主意.

所以我的问题是,我如何实施上面描述的内容;或者,如果那是罕见的,那么获得与我刚刚描述的功能相似的功能的常见方法是什么?

推荐答案

这是您想要的吗?这对我来说很好.

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);
        }
    }

}

,然后

<?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>

以上所述是小编给大家介绍的在fxml中使用自定义控件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34090.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。