簡體   English   中英

在fxml中使用自定義控件

[英]Using custom Controls in fxml

假設我已經將javafx提供的默認TableView<T>類子類化,並創建了一個類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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM