我正在使用Eclipse製作java遊戲。當我導出到可運行jar並嘗試在不同計算機上運行遊戲時,圖像不可見。檢查網絡和堆棧溢出後,類似的問題,我認爲這與我使用ImageIcon
而不是ImageIO
有關。但是,我不知道如何更改我的代碼,以便我使用ImageIO
而不是ImageIcon
上傳圖像。用ImageIO替換ImageIcon以加載圖像
下面是一個使用ImageIcon
加載圖像
void loadImage() {
ImageIcon earth_image_icon = new ImageIcon("earth2.png");
earth = earth_image_icon.getImage();
ImageIcon sun_image_icon = new ImageIcon("sun2.png");
sun = sun_image_icon.getImage();
ImageIcon asteroid_image_icon = new ImageIcon("asteroid.png");
asteroid = asteroid_image_icon.getImage();
ImageIcon bg_image_icon = new ImageIcon("bg_pr.png");
background = bg_image_icon.getImage();
ImageIcon shipA_image_icon = new ImageIcon("ship_alpha.png");
ship_on_asteroid = shipA_image_icon.getImage();
ImageIcon ship_image_icon = new ImageIcon("ship_beta.png");
ship_no_thrust = ship_image_icon.getImage();
ImageIcon shipL_image_icon = new ImageIcon("ship_betaL.png");
ship_left_thrust = shipL_image_icon.getImage();
ImageIcon shipR_image_icon = new ImageIcon("ship_betaR.png");
ship_right_thrust = shipR_image_icon.getImage();
ImageIcon shipU_image_icon = new ImageIcon("ship_betaU.png");
ship_up_thrust = shipU_image_icon.getImage();
ImageIcon shipD_image_icon = new ImageIcon("ship_betaD.png");
ship_down_thrust = shipD_image_icon.getImage();
ImageIcon leftarrow_image_icon = new ImageIcon("leftarrow.png");
leftarrow = leftarrow_image_icon.getImage();
ImageIcon rightarrow_image_icon = new ImageIcon("rightarrow.png");
rightarrow = rightarrow_image_icon.getImage();
ImageIcon downarrow_image_icon = new ImageIcon("downarrow.png");
downarrow = downarrow_image_icon.getImage();
ImageIcon uparrow_image_icon = new ImageIcon("uparrow.png");
uparrow = uparrow_image_icon.getImage();
}
這裏是將圖像繪製到的JPanel作爲一個例子
void drawEarth(Graphics g) {
g.drawImage(earth, earth_x_coordinate, earth_y_coordinate, this);
Toolkit.getDefaultToolkit().sync();
}
如何轉換的方法之一方法使用ImageIO
?我已經檢查了Oracle文檔,但是我正在嘗試將它整理出來,並且我對編程和Java非常陌生。
更新它已經建議this可能是解決我的具體問題,但我想這個帖子上給出的答案,他們並沒有對我的情況下工作。
圖像存儲在與源的關係中? – MadProgrammer 2015-03-19 01:32:33
圖像存儲在項目文件夾中,而不是源文件夾中。不過,我已經嘗試將圖像存儲在源文件夾中,並將圖像放入資源文件夾並將該文件夾添加到構建路徑。 – abaxtastic 2015-03-19 01:33:51
如果圖像存儲在項目文件夾中,則需要確保它們與jar一起包含並駐留在執行上下文的上下文中(因爲搜索路徑將從該點開始是相對的)。如果它們包含在「jar」(捆綁/嵌入)中,則需要使用類似於getClass()。getResource(「...」)'來加載它們。在這種情況下,路徑應該是來自源目錄根目錄(不包括'src'文件夾)的圖像的絕對路徑。 – MadProgrammer 2015-03-19 01:36:14