将场景从一个包切换到另一个包javafx

Switch scenes from one package to another package javafx

我有两个包 p1 和 p2。

P1 包含主要 class、控制器 class 和一个 fxml 文件。 P2 包含控制器 class 和一个 fxml 文件。

我想从 p1 fxml 文件切换到 p2 fxml 文件。

这是我试过的代码。这是在 P1 包中。

public void btncontinue(ActionEvent event)throws IOException {
        String filepath = "file:///D:/Programs/InteliJProjects/C/src/p1/sample2.fxml";
        Parent nextScene = FXMLLoader.load(getClass().getClassLoader().getResource(filepath));
        Scene scene = new Scene(nextScene);
        Stage stage = (Stage)((Node)event.getSource()).getScene().getWindow();
        stage.setScene(scene);
        stage.show();
    }

我收到的错误是 Location is required.

好吧,我检查过这是从场景 1 到场景 2 的代码

 package sample;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;


import java.io.IOException;

public class sample
{

    @FXML
    RadioButton male;

    @FXML
    AnchorPane rootPane;


    public void add() throws IOException
    {
        AnchorPane pane = FXMLLoader.load(getClass().getResource("two.fxml"));
        rootPane.getChildren().setAll(pane);
    }

}

这就是如何return从场景 2 到场景 1

package sample;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;

import java.io.IOException;

public class Two
{
    @FXML
    Button back;

    @FXML
    AnchorPane secPane;

    public void returnBack() throws IOException
    {
        AnchorPane pane = FXMLLoader.load(getClass().getResource("sample.fxml"));
        secPane.getChildren().setAll(pane);
    }
}

我试过了,效果很好希望对你有帮助