[英]JavaFX - Access fx:id from nested FXML
因此,这是我的主要FXML文件,称为“ Home.fxml”:
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
<fx:include source="MenuBar.fxml" />
<Label alignment="CENTER" maxWidth="1.7976931348623157E308" text="Welcome to MSMusic" textAlignment="CENTER">
<font>
<Font size="62.0" />
</font>
</Label>
<fx:include source="PlayerElement.fxml" />
</VBox>
在该文件中,我包括一个音乐播放器元素,该元素的标签带有fx:id'songTime',当我尝试在Home.fxml的Controller中使用'songTime'时,我得到了NullPointerException,因为fx:id来自内部嵌套的fxml似乎不可用。 有没有简单的方法可以做到这一点?
通常,对于在其中出现UI的FXML文件,将UI控件公开在控制器之外是不正确的做法。
您可以将控制器从随附的FXML文件注入到Home.fxml
文件的控制器中:
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
<fx:include source="MenuBar.fxml" />
<Label alignment="CENTER" maxWidth="1.7976931348623157E308" text="Welcome to MSMusic" textAlignment="CENTER">
<font>
<Font size="62.0" />
</font>
</Label>
<fx:include fx:id="player" source="PlayerElement.fxml" />
</VBox>
在Home.fxml
的控制器中,您可以执行
public class HomeController {
@FXML
private PlayerElementController playerController ;
// ...
}
其中, PlayerElementController
是PlayerElement.fxml
文件的控制器类。 这在文档的“嵌套控制器”下进行了描述 ,但实际上仅使用名称为fx:id
的字段作为fx:include
并附加了"Controller"
,因此此处的fx:id="player"
包括允许您将包含的FXML文件的控制器实例注入到字段playerController
。
现在,只需在PlayerElementController
定义一些用于设置所需文本的方法即可:
public class PlayerElementController {
@FXML
private Label songTime ;
// note: might want to make the parameter a more appropriate type than string,
// and perform the conversion to a string in this method...
public void setSongTime(String songTime) {
this.songTime.setText(songTime);
}
// and similarly here for the return type
public String getSongTime() {
return songTime.getText();
}
// ...
}
现在回到您的HomeController
您需要做的就是
playerController.setSongTime(...);
设置文本。 如果需要与标签关联的其他功能,只需定义与所需行为对应的适当方法即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.