嵌入按钮的图像不会显示

时间:2015-04-28 02:28:16

标签: java image button javafx

我正在尝试创建一个按钮,其左侧出现了一个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

1 个答案:

答案 0 :(得分:1)

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

  

表示用于获取像素数据的URL的字符串

即。你需要一个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())也有效。)