JavaFX中两个fxml文件和控制器的问题

时间:2017-12-10 19:32:33

标签: java javafx fxml

Screenshot of errors

我有班级。它位于包" view"

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
    try {
       AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("start.fxml"));
        Scene scene = new Scene(root, 757, 562);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Course Work");
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}
}

成功加载文件start.fxml。它也位于包" view"。

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="562.0" prefWidth="757.0" styleClass="anchor-pane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.Start">
   <children>
      <Button layoutX="48.0" layoutY="466.0" mnemonicParsing="false" onAction="#start" text="Ок">
         <font>
            <Font size="14.0" />
         </font>
      </Button>
   </children>
</AnchorPane>

此start.fxml的控制器位于包&#34; controller&#34;。

public class Start {
private Stage stage;

    @FXML
    public void start(ActionEvent event) throws Exception { 
       try {
            AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("sample.fxml"));
            Scene scene = new Scene(root, 757, 562);
            stage.setScene(scene);
            stage.setTitle("Course Work");
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法&#34;开始&#34;我想使用sample.fxml创建新的舞台。但是我遇到了一些问题。例如 - java.lang.NullPointerException。我怎么能适合它?

1 个答案:

答案 0 :(得分:-1)

在这种情况下NullPointerException可能是因为JavaFX框架无法找到提供的.fxml文件。您应该提供完全限定的名称,例如如下:

public Node loadResource(String resource) {
    try {
        return FXMLLoader.load(getClass().getResource("/com/google/resources/" + resource));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

在上面的代码中,.fxml文件位于com.google.resources