嵌入在按钮上的图像不会显示

Image embedded on button wont show

我正在尝试创建一个带有嵌入图像的按钮,该图像出现在左侧,但显然我做错了什么,因为我一直得到 3。所以我的问题是如何正确获取我的要显示的图像?这是我的。

    Image buttonIcon = new Image("C:/Users/emanu_000/Documents/Excersise4/src/my-profile-icon.png");
    ImageView iconView = new ImageView(buttonIcon);

    getPicButton = new Button("Get Picture",iconView);
    getPicButton.setContentDisplay(ContentDisplay.LEFT);
    mainPane.setConstraints(getPicButton, 1, 3);
    mainPane.getChildren().add(getPicButton);

这是堆栈跟踪

Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in        Application start method
at       com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication2(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda/2093176254.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown  protocol: c
 at javafx.scene.image.Image.validateUrl(Image.java:1102)
at javafx.scene.image.Image.<init>(Image.java:608)
at com.company.Main.start(Main.java:134)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication19(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda/135888596.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait2(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda/1904663592.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null0(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda/1835699047.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater1(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda/2102390814.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null5(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda/216334026.run(Unknown Source)
... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
at java.net.URL.<init>(URL.java:593)
at java.net.URL.<init>(URL.java:483)
at java.net.URL.<init>(URL.java:432)
at javafx.scene.image.Image.validateUrl(Image.java:1096)
... 16 more

根据Javadocs for Image,你传递的参数是

the string representing the URL to use in fetching the pixel data

即此处需要 URL,而不是文件系统路径。

你可以做到

File file = new File("C:/Users/emanu_000/Documents/Excersise4/src/my-profile-icon.png");
URL url = file.toURI().toURL();
Image image = new Image(url.toExternalForm());

(我认为,更简单地说,new Image(file.toURI().toString()) 也有效)。