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

时间:2020-08-08 10:06:07

标签: java javafx

我有两个软件包p1和p2。

P1包含主类,控制器类和一个fxml文件。 P2包含控制器类和一个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 个答案:

答案 0 :(得分:0)

好,我已经检查了这是从场景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);
    }

}

这是从场景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);
    }
}

我已经尝试过了,希望它能对您有所帮助