afficher une image dans un JPanel
Bonjour,
Je veux créer un composant JPanel avec une image, voici mon code :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.awt.*;
import javax.swing.*;
public class Picture extends JPanel {
private Image img;
public Picture(String file) {
img = new ImageIcon(getClass().getResource(file)).getImage();
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (img == null) return;
int w = img.getWidth(this);
int h = img.getHeight(this);
boolean zoom = (w > getWidth() || h > getHeight());
if (zoom) g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
else g.drawImage(img, (getWidth()-w)/2, (getHeight()-h)/2, this);
}
} |
En fait ce code n'est pas de moi, il vient d'ici:
http://cui.unige.ch/~deriazm/javasources/Picture.java
Mais quand je le lance, j'ai une erreur dans le constructeur à la ligne img = new ImageIcon ...
avec le message 'Exception in thread "main" java.lang.NullPointerException'
Qu'est ce que j'ai oublié ?
merci,
Nico