我的代码不知何故无法加载 fxml 文件。我检查了文件的路径,它是正确的。我错过了什么吗?我知道我可以使用 SceneBuilder 来设计 GUI 并使用单独的 Controller 文件添加功能。
JAVA代码:
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main4 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
StackPane page = (StackPane) FXMLLoader.load(Main4.class.getResource("/home/emil/code/javaGUI/src/sample.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("FXML is Simple");
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(Main4.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
FXML 代码:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<StackPane prefHeight="150.0" prefWidth="200.0" xmlns:fx="http://javafx.com/fxml">
<children>
<Button mnemonicParsing="false" text="Button" />
</children>
</StackPane>
最佳答案
您使用了源代码目录中的绝对路径,而不是完整的文件系统路径。
例如 如果你的java源文件的包是com.learnjavafx。那么文件名应该像/com/learnjavafx/sample.fxml。
但对于您的情况,只需使用sample.fxml,因为源代码不属于任何特定包。
关于java - 无法加载 fxml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35493641/