How to add an image to a JPanel?

前端 未结 14 1726
陌清茗
陌清茗 2020-11-22 00:01

I have a JPanel to which I\'d like to add JPEG and PNG images that I generate on the fly.

All the examples I\'ve seen so far in the Swing Tutorials, specially in the

14条回答
  •  没有蜡笔的小新
    2020-11-22 00:48

    Fred Haslam's way works fine. I had trouble with the filepath though, since I want to reference an image within my jar. To do this, I used:

    BufferedImage wPic = ImageIO.read(this.getClass().getResource("snow.png"));
    JLabel wIcon = new JLabel(new ImageIcon(wPic));
    

    Since I only have a finite number (about 10) images that I need to load using this method, it works quite well. It gets file without having to have the correct relative filepath.

提交回复
热议问题