繁体   English   中英

自定义控件中的javafx 8顺序子级

[英]javafx 8 order children in custom control

我正在编写一个自定义控件,如果在表单中的验证失败,它将在工具提示中显示错误图标和消息。 我的没有自定义控件的版本如下所示:

<HBox>
    <TextField fx:id="name"></TextField>
    <Label fx:id="error" focusTraversable="false" visible="false">
        <graphic>
            <ImageView fitHeight="24.0" fitWidth="24.0" pickOnBounds="true" preserveRatio="true"/>
        </graphic>
        <tooltip>
            <Tooltip fx:id="errorTooltip"/>
        </tooltip>
    </Label>
</HBox>

结果是这样的:

验证错误

我创建自定义控件的努力导致了这一点:

<fx:root type="javafx.scene.layout.HBox" xmlns:fx="http://javafx.com/fxml">
    <children/>
    <Label fx:id="error" focusTraversable="false" visible="false">
        <graphic>
            <ImageView fitHeight="24.0" fitWidth="24.0" pickOnBounds="true" preserveRatio="true"/>
        </graphic>
        <tooltip>
            <Tooltip fx:id="errorToolTip"/>
        </tooltip>
    </Label>
</fx:root>

这是fxml背后的代码:

package control;

[imports omitted for brevity]

@DefaultProperty(value = "children")
public final class ValidatedControl extends HBox implements Initializable {

    @FXML
    private Label error;
    @FXML
    private Tooltip errorToolTip;
    private StringProperty errorToolTipProperty;

    public ValidatedControl() {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("ValidatedControl.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    public void setErrorToolTip(final String errorToolTip) {
        this.getErrorToolTipProperty().setValue(errorToolTip);
    }

    public String getErrorToolTip() {
        return this.getErrorToolTipProperty().getValueSafe();
    }

    @Override
    public void initialize(final URL location, final ResourceBundle resources) {
        this.errorToolTip.textProperty().bind(this.getErrorToolTipProperty());
        this.error.visibleProperty().bind(this.getErrorToolTipProperty().isNotEmpty());
    }

    public StringProperty getErrorToolTipProperty() {
        if (this.errorToolTipProperty == null) {
            this.errorToolTipProperty = new SimpleStringProperty();
        }
        return this.errorToolTipProperty;
    }
}

我可以在fxml中使用该控件,但是我添加的子组件始终是最后一个子组件,这意味着错误图标显示在其左侧。

在错误的一面

我的控件是这样使用的:

<ValidatedControl>
    <TextField>
    </TextField>
</ValidatedControl>

如何获得在右侧显示图标的信息?

现在,我知道您的问题了。 在FXML中添加ValidatedControl时,这可能无法解决您的问题,但是当您以编程方式执行此操作时,请尝试以下操作:

ValidatedControl vc = new ValidatedControl();
TextField textField = new TextField();
vc.getChildren().add(textField);
textField.toBack();

另一种方法是按照ItachiUchiha的方法在FXML中添加第一个孩子的Pane 但是,不要覆盖getChildren()方法,而是编写一个新方法addNode(Node n)并将该节点添加到窗格中。

忘记我的第一个答案;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM