在fxml中使用自定义控件

qua*_*yte 4 java javafx custom-controls

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

现在我想在fxml文件中使用我的自定义类的实例,就像我将使用所有默认控件一样.这正是我的问题,我不知道如何做到这一点,或者这是否是一个好的/共同的设计决定.

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

我想象一种类似于.NET的WPF中的语法和功能,你可以在任何其他控件中使用标记中的自定义类,因为xaml和c#比java和fxml更紧密耦合.

从我目前的观点来看,我所描述的内容无法完成,而我最终只会使用非常少量的fxml和更多代码,即使对于刚刚布局的部分也是如此.例如,我不想使用这样的代码:

 AnchorPane.setRightAnchor(customControl, 65.0);
Run Code Online (Sandbox Code Playgroud)

因为我相信在我的fxml中定义它是一个好主意.

所以我的问题是,我如何实现上面所描述的内容; 或者,如果这种情况不常见,那么获得类似功能的常用"最佳实践"方法是什么?

Jam*_*s_D 7

这是你在找什么?这对我来说很好.

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

}
Run Code Online (Sandbox Code Playgroud)

然后

<?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>
Run Code Online (Sandbox Code Playgroud)