【发布时间】:2015-04-03 16:41:11
【问题描述】:
我正在编写一个自定义控件,如果表单中的验证失败,它会在工具提示中显示错误图标和消息。我没有自定义控件的版本如下所示:
<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>
如何让它在右侧显示图标?
【问题讨论】:
-
有多种方法可以实现这一点。一种方法是将
HBox作为根。其中有另一个HBox以及您的标签。覆盖getChildren()并从中返回子HBox的子代。 -
在使用自定义控件的第二个版本中,包含 TextField 和错误图标的父节点是什么?你能在你布局 TextField 和错误图标的地方显示 fxml/Java 布局吗?
-
@ItachiUchiha:我试过你的解决方案。在初始化过程中,java 使用 getChildren 来构建 fxmlDOM [原文如此?] 这意味着子 HBox 将是它自己的父级。结尾是 IllegalArgumentException: Children: cycle detected: parent = HBox[id=content], node = HBox[id=content]