我的java程序中没有显示图像

时间:2016-06-30 14:47:06

标签: java eclipse java-2d

最近我决定开始学习如何使用JAVA(eclipse)制作2D游戏,所以我在网上找到了一个教程,展示了如何用java制作superMari游戏,我写了他写的相同代码,我一步一步跟着他做了,这不是一件很重要的事情,不幸的是他的代码显示,在一个窗口中有两个图像,然后我只显示没有图像的窗口,我确保你导入了将两张图片放在一个包中,以避免出现各种问题,但仍然没有显示任何问题。

我的代码有两个类," main"和#34;场景",在这里,希望有人会为我找到一个解决方案,谢谢你们!

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);
    }

}

2 个答案:

答案 0 :(得分:1)

您尚未正确命名paintComponent方法,因此未被覆盖。

正确的名称是paintComponent而不是paintCompenent

public class Example extends JPanel {

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

答案 1 :(得分:-1)

您可以通过执行以下操作来确定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());
}