简体   繁体   English

ImageView 在 JavaFX 中不起作用

[英]ImageView doesn't work in JavaFX

not just this, other codes have the same problem.不仅如此,其他代码也有同样的问题。 just can't use ImageView.就是不能使用 ImageView。

Environment : macOS, IntelliJ环境:macOS、IntelliJ

Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found引起: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;
    }
}

The Image constructor takes a url as a parameter. Image构造函数接受一个 url 作为参数。 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.显然, /Users/fangyuan/Desktop/PIC.png不会在您的类路径中。

To read from a file instead of the classpath, then stick the file:// protocol in front of the path you want to read:要从文件而不是类路径中读取,请在要读取的路径前添加file://协议:

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

Or或者

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

which would output the same thing.这将输出相同的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM