[Débutant] Impossible de modifier la méthode PaintComponent(), renvoit NullException?
Bonjour, j'essaie d'automatiser la modification (réduction de taille) de l'affichage d'une image en modifiant la méthode paintComponent() de JPanel. A la compilation il n'y a aucun problèmes mais dès que je lance l'application je me retrouve avec une exception implicite : NullPointerException dont je n'arrive pas a me dépêtrer ne trouvant pas l'erreur.
Etant un petit débutant :oops: , je vous supplie de bien vouloir éclairer ma lanterne en pointant mon erreur.:fessee:
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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| /**
* §§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§
* § AUTOMATISATION DE LA MODIFICATION D'UNE IMAGE §
* § SUR UN JPANEL §
* §§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§§
*LA COMPILATION DE RENVOIT PAS D'ERREUR MAIS AU LANCEMENT UNE EXCEPTION IMPLICITE
*
*AMD64:$ java TestImageModif
*Exception in thread "main" java.lang.NullPointerException
* at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
* at TestImageModif$ImagePerso.<init>(TestImageModif.java:39)
* at TestImageModif.initialize(TestImageModif.java:24)
* at TestImageModif.<init>(TestImageModif.java:13)
* at TestImageModif.main(TestImageModif.java:58)
*/
import java.awt.*;
import javax.swing.*;
public class TestImageModif extends JFrame {
public TestImageModif() {
super();
initialize();
}
private JPanel jContentPane = null;
private String image = "Image001.jpg";//IMAGE A AFFICHER & MODIFIER
private JPanel monImage;//CONTENEUR DE L'IMAGE
private void initialize() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,300,300);
monImage = new ImagePerso();//CLASS IMAGEPERSO() REDEFINIE JPANEL
this.setContentPane(monImage);
}
class ImagePerso extends JPanel {
private Image img;
public ImagePerso() {
img = new ImageIcon(getClass().getResource(image)).getImage();
repaint();
}
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);
}
}
public static void main(String arg[]) {
TestImageModif test = new TestImageModif();
test.setVisible(true);
}
} |