ImageView doesn't work in JavaFX

2020-05-07 00:18发布

问题:

not just this, other codes have the same problem. just can't use ImageView.

Environment : macOS, IntelliJ

Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found

public class ShowHboxVbox extends Application {

    static  String s = "/Users/fangyuan/Desktop/PIC.png";

    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(getHbox());

        Scene scene = new Scene(borderPane);
        primaryStage.setTitle("title");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private HBox getHbox() {
        HBox hBox = new HBox(15);
        hBox.setPadding(new Insets(15,15,15,15));
        hBox.setStyle("-fx-background-color: gold");
        hBox.getChildren().add(new Button("computer science"));
        hBox.getChildren().add(new Button("chemist"));
        ImageView imageView = new ImageView(new Image(s));
        hBox.getChildren().add(imageView);
        return hBox;
    }
}

回答1:

The Image constructor takes a url as a parameter. If you don't put a protocol in it, then it assumes that the item comes off of the classpath. Obviously, /Users/fangyuan/Desktop/PIC.png won't be in your classpath.

To read from a file instead of the classpath, then stick the file:// protocol in front of the path you want to read:

file:///Users/fangyuan/Desktop/PIC.png

Or

Paths.get("/Users/fangyuan/Desktop/PIC.png").toUri().toString()

which would output the same thing.



标签: java javafx