无法在Java上加载图像(BlueJ)

时间:2014-01-27 15:55:45

标签: java image awt bluej

我试图将我的图像加载到Java上,但在运行代码时,我的JFrame中没有任何内容。

我这样做的方式是从我的主要部门调用我的图像功能:

    import java.awt.*;              // Graphics stuff from the AWT library, here: Image
    import java.io.File;            // File I/O functionality (for loading an image)
    import javax.swing.ImageIcon;   // All images are used as "icons"



  public class GameImage
    {
  public static Image loadImage(String imagePathName) {

    // All images are loades as "icons"
    ImageIcon i = null;

    // Try to load the image
    File f = new File(imagePathName);


    if(f.exists()) {  // Success. Assign the image to the "icon"
        i = new ImageIcon(imagePathName);
    }
    else {           // Oops! Something is wrong.
        System.out.println("\nCould not find this image: "+imagePathName+"\nAre file       name and/or path to the file correct?");            
        System.exit(0);
    }

    // Done. Either return the image or "null"
    return i.getImage();

} // End of loadImages method

}

然后在这里调用它:

        GI_Background = GameImage.loadImage("Images//background.jpg");
    GI_DuskyDolphin = GameImage.loadImage("Images//DuskyDolphin.jpg");

如果这还不够,我很乐意提供剩下的代码:) 感谢

2 个答案:

答案 0 :(得分:1)

如果图像是应用程序的一部分,不使用文件,而是使用java资源机制。

    URL imageUrl = getClass().getResource("/Images/background.jpg");
    return new ImageIcon(imageURL).getImage();

未找到时,资源URL将返回null。 如果应用程序打包在.jar中,您可以使用7zip / WinZip左右打开它,并检查路径。它必须区分大小写,并使用/(不反斜杠)。

答案 1 :(得分:0)

我不太确定你想要实现的目标...... 使用方法加载图像,这就足够了:

private Image loadImage(String fileName){
    return (new ImageIcon(fileName)).getImage();
}

之后,我会以Image为背景创建一个JLabel;

ImageIcon image = getImage( filename );    

JLabel imageLabel = new JLabel( image );
imageLabel.setSize( image.getIconHeight, image.getIconWidth );

JFrame frame = new JFrame();
frame.add( imageLabel );

试试这个,如果我不为你工作,或者你不想要你,那么请随时再次学习:)