Search code examples
javaswingjpanelimageicon

ImageIcon.paintIcon does not draw image on JPanel


I'm trying to draw a .png on a JPanel. I imported it using an ImageIcon constructor, and drew it in my custom panel's paintComponent.

My sscce:

package mypackage;

import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPanel extends JPanel {

    static JFrame frame;
    static MyPanel panel;
    static ImageIcon icon;

    public static void main(String[] args) {
        icon = new ImageIcon(MyPanel.class.getResource("MyImage.png"));
        frame = new JFrame();
        panel = new MyPanel();
        frame.setSize(500, 500);
        frame.add(panel);
        frame.setVisible(true);
        frame.repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        icon.paintIcon(panel, g, 100, 100);
    }
}

I expected the image, which is just a couple shapes on a white background, to display at (100, 100) on the panel. Instead, a blank screen:

Blank panel where I expected my image to be drawn

The fact that no error occurs means the program is finding the file properly.

The image is in my Eclipse project in the same package as the class:

Project setup

Why is this happening? How do I fix it?


Solution

  • As the code looks correct, I suggest that the resource is not being loaded correctly.

    Place the png file in your classpath. Eg. I would have a directory:

    ~/ProjectRoot/resources/mypackage/
    

    Then include resources in the classpath. In eclipse you can setup the classpath via

    Project -> Properties -> Java Build Path -> Add Class Folder

    BufferedImage img = 
        ImageIO.read(MyPanel.class.getResourceAsStream("MyImage.png"));
    

    That throws an exception if the image isn't found. You can use it to make an ImageIcon.