我正在尝试在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

请帮忙。谢谢你们。

最佳答案

您甚至对没有类路径的图像都使用getClass()。getResourceAsStream(imageResource),如果您不是从类路径中加载,则直接传递URL-String:

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

10-07 19:43
查看更多