我有主要的应用程序类,做以下只是罚款:
@Override public void start(Stage primaryStage) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource( "RecordScreen.fxml")); Parent root = (Parent) loader.load(); Scene newScene = new Scene(root); Stage newStage = new Stage(); newStage.setScene(newScene); newStage.show(); } catch (Exception e) { e.printStackTrace(); } }
它启动显示人物的表视图.我选择一个人,点击编辑按钮,并尝试启动一个窗口,让我编辑它们.
@FXML public void editPerson() { try { FXMLLoader loader = new FXMLLoader(getClass().getResource( "PersonEditor.fxml")); PersonEditorCtrl ctrl = loader.getController(); ctrl.init(table.getSelectionModel().getSelectedItem()); Parent root = (Parent) loader.load(); Scene newScene = new Scene(root); Stage newStage = new Stage(); newStage.setScene(newScene); newStage.show(); } catch (Exception e) { e.printStackTrace(); } }
问题是getController返回null.我过去2周一直在追随这个模式,没有任何问题.我现在做错了什么?这些无法追溯的错误正在恶化!
这是我的两个fxmls:
带桌面的屏幕:
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.RecordsCtrl"> <!-- TODO Add Nodes --> <children> <VBox id="VBox" alignment="CENTER" spacing="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> <children> <TableView fx:id="table" prefHeight="-1.0" prefWidth="-1.0"> <columns> <TableColumn prefWidth="75.0" text="Name" fx:id="nameCol" /> <TableColumn prefWidth="75.0" text="Age" fx:id="ageCol" /> </columns> </TableView> <Button mnemonicParsing="false" onAction="#editPerson" text="Edit" /> </children> </VBox> </children> </AnchorPane>
人物编辑:
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.PersonEditorCtrl"> <!-- TODO Add Nodes --> <children> <VBox layoutX="0.0" layoutY="0.0" prefHeight="-1.0" prefWidth="-1.0"> <children> <TextField fx:id="nameField" prefWidth="200.0" /> <TextField fx:id="ageField" prefWidth="200.0" /> <Button mnemonicParsing="false" text="Button" /> </children> </VBox> </children> </AnchorPane>
解决方法
改变这个
@FXML public void editPerson() { try { FXMLLoader loader = new FXMLLoader(getClass().getResource( "PersonEditor.fxml")); PersonEditorCtrl ctrl = loader.getController(); ctrl.init(table.getSelectionModel().getSelectedItem()); Parent root = (Parent) loader.load(); Scene newScene = new Scene(root); Stage newStage = new Stage(); newStage.setScene(newScene); newStage.show(); } catch (Exception e) { e.printStackTrace(); } }
对此:
@FXML public void editPerson() { try { FXMLLoader loader = new FXMLLoader(getClass().getResource( "PersonEditor.fxml")); Parent root = (Parent) loader.load(); PersonEditorCtrl ctrl = loader.getController(); ctrl.init(table.getSelectionModel().getSelectedItem()); Scene newScene = new Scene(root); Stage newStage = new Stage(); newStage.setScene(newScene); newStage.show(); } catch (Exception e) { e.printStackTrace(); } }
您首先必须运行loader.load(),然后才能得到Controller.
帕特里克