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

gudnpqoy  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(378)

我正在尝试创建一个嵌入图像的按钮,该图像在左侧显示为48 x 48,但显然我做了一些不正确的事情,因为我一直得到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$launchApplication$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$2/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$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$52/135888596.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/1904663592.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$50/1835699047.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$49/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$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$38/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
2nc8po8w

2nc8po8w1#

根据javadocs Image ,传递的参数为
表示用于获取像素数据的url的字符串
i、 你需要一个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()) 也有效)。

相关问题