ImageView在JavaFX中不起作用 [英] ImageView doesn't work in JavaFX

查看:155
本文介绍了ImageView在JavaFX中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不仅如此,其他代码也有相同的问题.只是不能使用ImageView.

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

环境:macOS,IntelliJ

Environment : macOS, IntelliJ

由以下原因引起:java.lang.IllegalArgumentException:无效的URL:无效的URL或找不到资源

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;
    }
}

推荐答案

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.

要从文件而不是类路径中读取,然后将file://协议放在要读取的路径前面:

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

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

这将输出相同的内容.

这篇关于ImageView在JavaFX中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆