2015-07-11 115 views
0

當我爲「king.png」放置一個絕對路徑時,下面的代碼會拋出錯誤,但當我使用同一圖像的在線鏈接時,不會出現錯誤。我也嘗試過「king.png」作爲參數,因爲文件與.java文件存儲在同一文件夾中。有人可以解釋一些我得到這個錯誤的原因嗎?謝謝。圖像類無法找到文件?

我100%確定絕對文件路徑是正確的,我從右鍵點擊複製 - >複製文件路徑。

代碼:

Image pic = new Image("C:\\Users\\Jae\\IdeaProjects\\CSE114\\src\\ex15\\king.png"); 

錯誤:

"Exception in thread "main" 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 ex15.fileTest.main(fileTest.java:15) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) 
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) 
    ... 7 more" 

回答

1

假設波紋管例如用於顯示在您的場景中的圖像,你可以看到你應該添加file:圖像路徑的乞討

public class ImageTest extends Application 
{ 
    public void start(Stage primaryStage) 
    { 
     VBox vBox = new VBox(); 

     Image image = new Image("file:C:\\Users\\Elyas\\Desktop\\New folder (2)\\1.jpg"); 
     ImageView imageView = new ImageView(image); 

     vBox.getChildren().addAll(imageView); 

     Scene scene = new Scene(vBox,100,100); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

    } 

    public static void main(String[] args) 
    { 
     launch(); 
    } 

}