图片未显示在我的 java 程序中

Images no displaying in my java program

最近我决定开始学习如何使用 JAVA ( eclipse ) 制作 2D 游戏,所以我在网上找到了一个教程,展示了如何使用 java 制作 superMari 游戏,我写了相同的代码他写了,我一步一步地跟着他做了,这不是什么大不了的事,不幸的是,他的代码显示,执行后,一个 window 有两个图像,而我的只显示 window 没有图像,我向你保证我导入了两个图像并将它们放在一个包中以避免各种问题,但它仍然没有显示任何内容。

我的代码有两个类、"main"和"Scene",就在这里,希望有人能帮我找到解决办法,谢谢大家!

Main.java :

    package AiMEUR.AMiN.jeu;

import javax.swing.JFrame;

public class Main {

    public static Scene scene;

    public static void main(String[] args) {

        JFrame fenetre = new JFrame("Naruto in mario World!!");
        fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fenetre.setSize(700, 360);
        fenetre.setLocationRelativeTo(null);
        fenetre.setResizable(false);
        fenetre.setAlwaysOnTop(true);

        scene = new Scene();


        fenetre.setContentPane(scene);
        fenetre.setVisible(true);

    }

}

Scene.java :

 package AiMEUR.AMiN.jeu;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

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

@SuppressWarnings("serial")
public class Scene extends JPanel{

    private ImageIcon icoFond;
    private Image imgFond1;

    private ImageIcon icoMario;
    private Image imgMario;

    private int xFond1;

    public Scene(){

        super();

        this.xFond1 = -50;

        icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));
        this.imgFond1 = this.icoFond.getImage();
        icoMario =  new ImageIcon(getClass().getResource("/Images/1.png"));
        this.imgMario = this.icoMario.getImage();
    //  paintComponent(this.getGraphics());
    }

    public void paintCompenent(Graphics g){

        super.paintComponent(g);
        Graphics g2 = (Graphics2D)g;

        g2.drawImage(this.imgFond1, this.xFond1, 0, null);
        g2.drawImage(imgMario, 300, 245, null);
    }

}

您没有正确命名 paintComponent 方法,因此它没有被覆盖。

正确的名字是paintComponent而不是paintCompenent:

public class Example extends JPanel {

    @Override
    public void paintComponent(final Graphics g) {
        super.paintComponent(g);
    }
}

您可以通过执行以下操作来确定 ImageIcon 的加载状态:

 public Scene(){

    super();

    this.xFond1 = -50;

    icoFond = new ImageIcon(getClass().getResource("/Images/fond.gif"));

    int status = icoFond.getImageLoadStatus();
    switch (status) {
       case (MediaTracker.COMPLETE): {
          System.out.println("icoFond image has successfully loaded");
       }
       case (MediaTracker.ERRORED): {
          System.out.println("The icoFond image didn't load successfully");
          // probably because the image isn't actually at "/Images/fond.gif"
       }
    }


    this.imgFond1 = this.icoFond.getImage();
    icoMario =  new ImageIcon(getClass().getResource("/Images/1.png"));
    this.imgMario = this.icoMario.getImage();
//  paintComponent(this.getGraphics());
}