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:
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:
Why is this happening? How do I fix it?