Cannot load image in JavaFX

前端 未结 5 596
离开以前
离开以前 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:20

    Try this:

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

    If no protocol part indicating a URL (as http: or file:) is given, the file is supposed to reside in the default package. If you want it to put in a different package say com.my.images you add this information in a path like manner:

    img = new Image("/com/my/images/logo.png");
    
    0 讨论(0)
  • 2020-11-28 13:20

    This functions:

    Image image  = new Image(getClass()
            .getResourceAsStream("ChimpHumanHand.jpg"));
    
    0 讨论(0)
  • 2020-11-28 13:21
    Image img = new Image("file:/logo.png");
    

    or way with path:

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

    or

    File f = new File("c:\\logo.png");
    Image img = new Image(f.toURI().toString());
    

    also can use:

    new Image(file:src/logo.png) //root of project
    
    0 讨论(0)
  • 2020-11-28 13:33

    copy and paste the image into folder where source package(source packages in NetBeans IDE) is present. Then

    Image image = new Image("a1.jpg");
    Image image = new Image("File:a1.jpg");
    

    both will work.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题