Get image from relative path

前端 未结 8 1899
囚心锁ツ
囚心锁ツ 2021-02-03 13:01

In my project I have 2 packages. images - contain images and notification - contain java files

In notification/main.java I get Image o

相关标签:
8条回答
  • 2021-02-03 13:13

    / means an absolute path, save Java web-apps where / means relative to context. So, I would suggest to use relative URL, means get rid of that / in front, and then provide the right path.

    In case, even then you can't solve it, try to create a file on the same path you are looking for image. This way you will know that where you are looking exactly and where you should look.

    0 讨论(0)
  • 2021-02-03 13:13
    Toolkit tk = Toolkit.getDefaultToolkit();
    Class<? extends JFrame> j = YOURJFRAME.getClass();
    Image image = tk.createImage(j.getResource("/images/bell-icon16.png"));
    

    Try that code, if you have a JFrame that will work. If you have an Applet, then just use

    Toolkit tk = Toolkit.getDefaultToolkit();
    Image image = tk.createImage("images/bell-icon16.png");
    

    With applets you never want to use the / in the beginning, but if you have a JFrame, and you are using getResource, you need the / in the beginning of the Path.

    0 讨论(0)
  • 2021-02-03 13:16

    Incase the solution above doesn't work, try this (which worked for me):

    Image image = Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("/Images/bell-icon16.png"));
    
    0 讨论(0)
  • 2021-02-03 13:20
    setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("../resources/MainIcon.png")));
    
    0 讨论(0)
  • 2021-02-03 13:21
    SwingResourceManager.getImage(YourClass.class,"key-16x16.png");
    

    The getIcon method will return Icon as similar

    0 讨论(0)
  • 2021-02-03 13:26

    I'm using Netbeans to develop Java desktop application and I have solved my problem.

    Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();
    

    "this" is a class extends JFrame

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