引用Java FXML

时间:2015-08-18 18:57:51

标签: java javafx fxml

我有以下Java代码:

@DefaultProperty("strings")
public class CustomControl extends HBox {
 ChoiceBox<String> choiceBox = new ChoiceBox();
 public ObservableList<String> getStrings() {
  return choiceBox.getItems();
 }
}

以下FXML代码:

<CustomControl>
  <String fx:value="value1" />
  <String fx:value="value2" />
</CustomControl>

这样可以正常工作,但是如果我用以下FXML代码替换FXML代码,它就不起作用了:

<fx:define>
 <FXCollections fx:factory="observableArrayList" fx:id="collection">
  <String fx:value="value1" />
  <String fx:value="value2" />
 </FXCollections>
</fx:define>
...
<CustomControl>
 <fx:reference source="collection" />
</CustomControl>

当我运行它时,我得到以下类型的错误:

Unable to coerce [value1, value2] to class String.

我理解错误(它认为我想把整个字符串列表放到“strings”bean的第一个元素中,当我真的希望列表中的每个项目都被添加到“strings”bean中) ,但我不知道该怎么做我想做的事。 我的想法是,我试图在fxml文件的开头定义一个项目列表,以便我可以在fxml文件的其他部分多次引用该列表。我不知道这个列表中有多少项,所以我不想给每个项目它自己的id。如何在不获取父元素的情况下引用元素序列?或者有更好的方法来做到这一点吗?

1 个答案:

答案 0 :(得分:2)

在代码的第一个版本中,如果您向fx:id提供CustomControl

<CustomControl fx:id="customControl">
  <String fx:value="value1" />
  <String fx:value="value2" />
</CustomControl>

然后您应该能够使用

在FXML文件的其他地方引用该列表
${customControl.strings}

作为属性值,或

<fx:reference source="customControl.strings"/>

作为元素。

或者,我认为如果您在setStrings(...)类中定义CustomControl方法,第二种方法也适用,例如:

@DefaultProperty("strings")
public class CustomControl extends HBox {
 ChoiceBox<String> choiceBox = new ChoiceBox();
 public ObservableList<String> getStrings() {
  return stringsProperty().get();
 }
 public void setStrings(ObservableList<String> strings) {
  stringsProperty().set(strings);
 }
 public ObjectProperty<ObservableList<String>> stringsProperty() {
  return choiceBox.itemsProperty();
 }
}

使用此版本时,DefaultProperty似乎不尊重setStrings(...)方法,但如果您明确指定了它的工作属性:

<fx:define>
 <FXCollections fx:factory="observableArrayList" fx:id="collection">
  <String fx:value="value1" />
  <String fx:value="value2" />
 </FXCollections>
</fx:define>
...
<CustomControl>
 <strings>
  <fx:reference source="collection" />
 </strings>
</CustomControl>