Image won't display in JLabel

后端 未结 5 640
轻奢々
轻奢々 2021-01-21 03:17

I\'ve gone through every post I could find on this site and the Java tutorials and I still can\'t figure out why my code isn\'t working. Even when I copy/paste other peoples\'

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 03:59

    Just simply put your bg.png, alongside your gui.class file. That will do, if you write this code

    private ImageIcon getImage(String path)
    {
        URL url = getClass().getResource(path);
        System.out.println(url);
        if (url != null)
            return (new ImageIcon(url));
        return null;
    }
    

    More information can be found on Access to Resources

    Here path = "bg.png"; or if it's inside some folder than path = "someFolder/bg.png"; So you be writing something like this :

    JLabel lblNewLabel = new JLabel(getImage("bg.png"));
    lblNewLabel.setBounds(30, 30, 100, 100);
    

    Hope that might help.

    Regards

提交回复
热议问题