假设我对默认的 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);
因为我相信在我的 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>
关于java - 在 fxml 中使用自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895186/