我试图通过
加载新的FXMLURL url = this.getClass().getClassLoader().getResource("pknn/fxml/CreateCharacter.fxml");if (url == null) return;
AnchorPane pane = FXMLLoader.load(url);
startPanel.getChildren().setAll(pane);
适用于带StartController的CreateCharacter.fxml
<AnchorPane fx:id="createCharacterPanel" onMouseEntered="#paneEventHandler" prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pknn.StartController">
但是当我尝试将另一个FXML加载到同一个场景时
URL url = this.getClass().getClassLoader().getResource("pknn/fxml/LockerRoom.fxml");
if (url == null) return;
AnchorPane pane = FXMLLoader.load(url);
createCharacterPanel.getChildren().setAll(pane);
它不起作用,即使我将其更改为
startPanel.getChildren().setAll(pane);
但它仍然不起作用。 这是我要加载的fxml。
<AnchorPane fx:id="lockerRoomPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pknn.LockerRoomController">
它有很多例外,如
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
...
Caused by: javafx.fxml.LoadException:
/Users/pknn/Study/ComPro/MonsterBattle/out/production/MonsterBattle/pknn/fxml/LockerRoom.fxml:10
at pknn.StartController.createCharacter(StartController.java:132)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.ReflectUtil can not access a member of class pknn.LockerRoomController with modifiers ""
如何解决?感谢
答案 0 :(得分:1)
您无法“覆盖”FXML中指定的控制器。如果您打算更改控制器(或具有构造函数参数的控制器),则必须从FXML中删除fx:controller
属性并在FxmlLoader中设置控制器:
fxmlLoader = new FXMLLoader(fxmlFileAsResource);
fxmlLoader.setController(yourControllerInstance);
Pane pane = fxmlLoader.load();
答案 1 :(得分:0)
这是在同一Scene
create_character.fxml
<AnchorPane fx:id="createCharacterPanel" fx:controller="sample.StartController" xmlns:fx="http://javafx.com/fxml" >
<children>
<Button text="Load" onAction="#handleLoadFXML" AnchorPane.topAnchor="0" AnchorPane.leftAnchor="0" />
<ScrollPane AnchorPane.topAnchor="30" AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.bottomAnchor="0">
<content>
<VBox fx:id="child"/>
</content>
</ScrollPane>
</children>
</AnchorPane>
pane_a.fxml和pane_b.fxml
<AnchorPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.SecondController">
<children>
<Label text="Pane A"/>
</children>
</AnchorPane>
<AnchorPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.SecondController">
<children>
<Label text="Pane B"/>
</children>
</AnchorPane>
加载文件的控制器
public class StartController {
@FXML
private AnchorPane createCharacterPanel;
@FXML
private VBox child;
private Parent loadFXML(String name) {
try {
return FXMLLoader.load(getClass().getResource(name));
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
@FXML
private void handleLoadFXML(ActionEvent event) {
child.getChildren().addAll(
loadFXML("pane_a.fxml"),
loadFXML("pane_b.fxml")
);
}
}