Mar*_*cel 2 java controller javafx view 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>
Run Code Online (Sandbox Code Playgroud)
在该文件中,我包含一个音乐播放器元素,该元素具有带有 fx:id 'songTime' 的标签,当我尝试在 Home.fxml 的控制器中使用 'songTime' 时,我得到一个 NullPointerException,因为 fx:id 来自内部嵌套的 fxml 似乎不可用。有没有一种简单的方法可以实现这一目标?
在控制器外部公开 UI 控件以供其所在的 FXML 文件使用通常是不好的做法。
You can inject the controller from the included FXML file into the controller for your Home.fxml file:
<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>
Run Code Online (Sandbox Code Playgroud)
and in the controller for Home.fxml you can do
public class HomeController {
@FXML
private PlayerElementController playerController ;
// ...
}
Run Code Online (Sandbox Code Playgroud)
where PlayerElementController is the controller class for the PlayerElement.fxml file. This is described under "Nested Controllers" in the documentation, but essentially just use a field whose name is the fx:id for the fx:include with "Controller" appended to it, so here fx:id="player" for the include allows you to inject the controller instance for the included FXML file to the field playerController.
Now just define some methods in PlayerElementController for setting the desired text:
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();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
Now back in your HomeController all you need do is
playerController.setSongTime(...);
Run Code Online (Sandbox Code Playgroud)
to set the text. If you need other functionality associated with the label, just define the appropriate methods corresponding to the behavior you need.
| 归档时间: |
|
| 查看次数: |
1909 次 |
| 最近记录: |