JavaFX按名称查找ToggleGroup类

时间:2015-01-26 12:42:01

标签: javafx

当我需要获取Button类时,我会做下一步:

Button B = (Button)scene.lookup("#ID");

如何查找ToggleGroup类?

1 个答案:

答案 0 :(得分:2)

查找通常不是很健壮,正如您在问题中指出的那样,您无法使用它们来访问场景图中不是节点的元素(例如切换组)。通常,您应该将元素注入控制器。

如果您正在动态生成FXML,或者由于某些其他原因无法创建控制器类,则可以访问FXML加载程序的命名空间。这是一张地图,可用于通过FXML中的fx:id属性查找对象。

所以如果你有一个带

的FXML文件
<VBox>
    <fx:define>
        <ToggleGroup fx:id="myToggleGroup"/>
    </fx:define>
    <children>
        <RadioButton text="A" toggleGroup="$myToggleGroup"/>
        <RadioButton text="B" toggleGroup="$myToggleGroup"/>
        <RadioButton text="C" toggleGroup="$myToggleGroup"/>
    </children>
</VBox>

然后您可以使用

检索切换组
FXMLLoader loader = new FXMLLoader(fxmlURL);
Parent root = loader.load();
Map<String, Object> fxmlNamespace = loader.getNamespace();

ToggleGroup toggleGroup = (ToggleGroup) fxmlNamespace.get("myToggleGroup");

当然,您可以对场景图元素执行相同的操作。以这种方式做事而不是使用CSS查找是有利的,因为一旦加载FXML文件就会完全填充命名空间。 (只有在应用CSS后,CSS查找才会起作用。)

此外,由于namespace只是一张地图,因此您可以动态查找通过调用fx:id定义的namespace.keySet(),因此无需事先知道哪些ID可能是定义的。

相关问题