【问题标题】:FileNotFound Exception when creating ImageViewer JavaFX [duplicate]创建图像查看器 JavaFX 时出现 FileNotFoundException [重复]
【发布时间】:2020-08-14 23:53:46
【问题描述】:

我正在尝试在 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();
    }

这是我的目录,你可以看到我的图片存储在里面。

非常感谢任何帮助。

【问题讨论】:

    标签: java image javafx netbeans imageview


    【解决方案1】:

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

    您构造的FileInputStream 将与当前工作目录相关,您无法控制运行时的内容。

    不要使用流,而是使用Image 构造函数,该构造函数采用字符串形式的 URL。这将相对于类路径进行解析:

        // 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      相关资源
      最近更新 更多