Cannot load image in JavaFX

前端 未结 5 606
离开以前
离开以前 2020-11-28 12:49

I tested this code in order to create dialog with image.

final int xSize = 400;
final int ySize = 280;
final Color backgroundColor = Color.WHITE;
final Strin         


        
5条回答
  •  再見小時候
    2020-11-28 13:35

    Simply replace this code:

    Image img = new Image("logo.png");
    

    with this

    Image img = new Image("file:logo.png");
    

    Docu reference. https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html

    When you pass a String to the Image class it can be handled in four different ways (copied from docu):

    // The image is located in default package of the classpath
    Image image1 = new Image("/flower.png");
    
    // The image is located in my.res package of the classpath
    Image image2 = new Image("my/res/flower.png");
    
    // The image is downloaded from the supplied URL through http protocol
    Image image3 = new Image("http://sample.com/res/flower.png");
    
    // The image is located in the current working directory
    Image image4 = new Image("file:flower.png");
    

    The file: prefix is simply an URI scheme, or in other words the counterpart to the http: protocol classifier. This also works in the file browser, or in the web browser... ;)

    For further reference, you can take a look at the wiki page of the file URI scheme: https://en.wikipedia.org/wiki/File_URI_scheme

    Happy Coding,

    Kalasch

提交回复
热议问题