如何使用位于当前工作目录之外的目录中的图像文件创建新的Image()

时间:2014-09-28 22:42:15

标签: image javafx imageview

我试图在TilePane中列出iamges。当我尝试使用如下地址创建图像new ImageView("address");时出现错误:

"file:D:/Chrysanthemum.jpeg/"

以上是在当前工作目录之外的目录中。其他图像在类路径中。

这里是scec中的其余代码:

public class TilePaneExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox(30);

        String[] imageResources = new String[]{
            //loading images
            "file:D:/Chrysanthemum.jpeg/",
            "ImageResources/faviicon.png",
            "ImageResources/jquery-logo.png",
            "ImageResources/linkedin_32.png",
            "ImageResources/loading1.png",
            "ImageResources/twitter.png",
            "ImageResources/twitter_32.png",
            "ImageResources/wp.png",};

        // Pane
        TilePane tilePane = new TilePane();
        tilePane.setHgap(5);
        tilePane.setVgap(5);

        for (final String imageResource : imageResources) {
            Image image = new Image(getClass().getResourceAsStream(imageResource));
            ImageView imageView = new ImageView(image);
            imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    File f = new File(imageResource);
                    String absolutePath = f.getAbsolutePath();
                    String folderPath = absolutePath.
                            substring(0, absolutePath.lastIndexOf(File.separator));
                    System.out.println(folderPath);
                    try {
                        // Desktop.getDesktop().open(new File("D:\\WAKILI\\WAKILIdb"));
                        Desktop.getDesktop().open(new File(folderPath));
                    } catch (IllegalArgumentException iae) {
                        System.out.println("File Not Found");
                    } catch (IOException ex) {
                        Logger.getLogger(TilePaneExample.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            tilePane.getChildren().add(imageView);
        }

        root.getChildren().addAll(tilePane);
        primaryStage.setTitle("TilePane Example");
        Scene scene = new Scene(root, 300, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

错误:

Caused by: java.lang.NullPointerException: Input stream must not be null

请帮忙。谢谢大家。

1 个答案:

答案 0 :(得分:6)

你正在使用getClass()。getResourceAsStream(imageResource)甚至你的无类路径图像,直接传递URL-String,用于你没有从类路径加载的情况:

Image image;
if(imageResource.startsWith("file:")) {
  image = new Image(imageResource);
} else {
  image = new Image(getClass().getResourceAsStream(imageResource));
}