2017-04-20 18 views
0

我想分配一個圖像作爲背景與擺動。我找到了多種方法來做到這一點,但我似乎總是遇到同樣的問題。我找到了一個不錯的自定義類在這裏使用>http://www.camick.com/java/source/BackgroundPanel.java將文件分配給圖像編譯錯誤:javax.imageio.IIOException

這裏是我使用的代碼...

編輯代碼:新增構造

import javax.imageio.ImageIO; 
import javax.swing.*; 
import java.awt.*; 
import java.io.File; 
import java.io.IOException; 

public class TestMain { 
    TestMain(){ 
     JFrame frame = new JFrame("Test"); 
     Image img = null; 
     File f = new File("../images/Background.png"); 
     img = ImageIO.read(getClass().getResource(f)); 
     System.out.println("File " + f.toString()); 


     BackgroundPanel background = new BackgroundPanel(img, BackgroundPanel.SCALED, 0.50f, 0.5f); 

     frame.setContentPane(background); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(200, 100); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) throws IOException{ 
     new TestMain(); 
    } 
} 

這裏是什麼形象看起來像......

enter image description here

當我嘗試運行這段代碼,我GE編譯錯誤Error:(14, 51) java: incompatible types: java.io.File cannot be converted to java.lang.String。如果有人能想出如何幫助我做到這一點,將不勝感激。

+0

錯誤i自我解釋,文件無法找到。問題是,文件存儲在與項目和類文件的關係中,從何處執行代碼,與文件存儲位置的關係 – MadProgrammer

+0

在同一個項目中,這是我正在使用的代碼行使圖像顯示一個標籤(相同的位置),它的工作原理是''charImgLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass()。getResource(image))。getImage()。getScaledInstance(100 ,100,「../ images/Character.png」.SCALE_SMOOTH)));' –

+0

Then'img = ImageIO.read(f);'should read'img = ImageIO.read(getClass()。getResource(image) );' - 我也想指出剛剛發佈的代碼不會編譯爲'Image#getScaledImage'的'hint'屬性是一個'int'而不是'String' ...所以,我不知道 – MadProgrammer

回答

1

In the same project, this is the line of code I'm using to make the image show up for a label (same location), and it works >charImgLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource(image)).getImag‌​e().getScaledInstanc‌​e(100, 100, "../images/Character.png".SCALE_SMOOTH)));

好吧,讓我們看看那裏的明顯編譯錯誤一秒鐘。

我假定imageString參考當前類裝載器範圍內的圖像的路徑,這意味着

img = ImageIO.read(f); 

實際上應該是

img = ImageIO.read(getClass().getResource(image)); 

假設圖像被存儲內類加載器上下文(即jar/classpath)和你指定的路徑是正確的,那麼這應該加載你的圖像