我有一个真正简单的JavaFX项目来教我自己如何使用testfx编写测试。我无法弄清楚如何防止自己复制我的 sample.fxml 文件。该项目的结构目前是:
My Main.java看起来像这样:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
static Stage stage;
@Override
public void start(Stage stage) throws Exception {
Main.stage = stage;
Parent root = FXMLLoader.load(getClass().getResource("../../resources/sample.fxml"));
Scene scene = new Scene(root, 300, 275);
stage.setTitle("FXML Welcome");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我无法从我的测试类中访问sample.fxml,并且重复学习testfx更容易 - 但它显然不是前进的方法。我也试过通过从我的测试类中调用start()来创建场景但是我得到一个错误,说不能多次调用launch()。
还有其他人遇到过这种情况并找到了前进的方向吗?
答案 0 :(得分:1)
为了避免重复你的.fxml文件(我认为这不太理想),我建议你只需从src / main / resources加载文件。您可以使用控制器的ClassLoader(或非测试代码中的任何其他类)来执行此操作。
String filename = "sample.fxml";
ClassLoader loader = Controller.class.getClassLoader();
File file = new File(loader.getResource(filename).getFile());
Parent root = FXMLLoader.load(loader.getResource(filename));