创建ImageViewer JavaFX时FileNotFound异常

时间:2020-04-30 14:57:58

标签: java image javafx netbeans imageview

我正在尝试在JavaFX中打开图像并收到此错误

Caused by: java.io.FileNotFoundException: calibre/Books/1.png (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)

我认为我的目录有误。

这是我创建图像的方法。

public class Calibre extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        FileInputStream input = new FileInputStream("calibre/Books/1.png");
        Image image = new Image(input);
        ImageView imageView = new ImageView(image);

        HBox hbox =  new HBox(imageView);

        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        root.setId("pane");
        Scene scene = new Scene(root);
        stage.setScene(scene);
        scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
        Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
        //Set Stage Boundaries to visible bounds of the main screen
        stage.setX(primaryScreenBounds.getMinX());
        stage.setY(primaryScreenBounds.getMinY());
        stage.setWidth(primaryScreenBounds.getWidth());
        stage.setHeight(primaryScreenBounds.getHeight());
        stage.show();
    }

File Directory

这是我的目录,您可以看到我的图像存储在其中。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

属于应用程序的图像是资源,而不是文件。在构建应用程序时,它们将与类文件一起部署(例如,将它们复制到build文件夹中,或包含在jar文件中,具体取决于您构建应用程序的方式。)

您构建的FileInputStream将相对于当前工作目录,并且您无法控制运行时的目录。

代替使用流,而使用采用字符串形式的URL的Image构造函数。这将相对于类路径解决:

    // FileInputStream input = new FileInputStream("calibre/Books/1.png");
    Image image = new Image("/calibre/Books/1.png");

如果出于某些原因您确实想提供Stream,则可以从资源中获取流:

    InputStream input = getClass().getResourceAsStream("/calibre/Books/1.png");
    Image image = new Image(input);