簡體   English   中英

無法在Java(BlueJ)上加載映像

[英]Cant Load Image on Java (BlueJ)

我試圖將圖像加載到Java上,但是在運行代碼時,我的JFrame中什么也沒出現。

即時通訊的方式是從我的主設備調用我的Image函數:

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

如果這還不夠,我將很樂意提供其余代碼:)謝謝

如果圖像是應用程序的一部分,請不要使用文件,而要使用Java資源機制。

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

找不到資源URL時將返回null。 如果應用程序打包在.jar中,則可以使用7zip / WinZip左右打開它,然后檢查路徑。 它必須區分大小寫,並使用/ (非反斜杠)。

我不太確定您要嘗試實現什么...用一種方法加載圖像,這就足夠了:

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

試試這個,如果我對你不起作用,或者不想讓你想要的話,請再次提問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM