我正在寫一個自定義控件,顯示錯誤圖標和工具提示中的消息,如果在窗體驗證失敗。我沒有自定義控件的版本是這樣的:javafx 8訂單兒童在自定義控制
<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'的子節點。 – ItachiUchiha 2015-04-03 17:42:10
在使用自定義控件的第二個版本中,包含TextField和錯誤圖標的父節點是什麼?您可以在佈局TextField和錯誤圖標的位置顯示fxml/Java佈局嗎? – Aaron 2015-04-03 20:59:53
@IchichiUchiha:我試過你的解決方案。在初始化期間,java使用getChildren來構建fxmlDOM [sic?],這意味着子HBox將成爲它自己的父類。最後是一個IllegalArgumentException:子項:檢測到循環:parent = HBox [id = content],node = HBox [id = content] – 2015-04-05 08:20:40