0
所以,當我嘗試下面的代碼:網址加載錯誤
//Main Class
package com.mgflow58.Main;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Game {
public static void main(String[] args) {
BufferedImage mainicon = null;
JFrame window = new JFrame("Guppy's Adventure");
window.add(new GamePanel());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
try {
String mainurlstring = "icon.gif";
URL mainurl = new URL(mainurlstring);
try {
mainicon = ImageIO.read(mainurl);
window.setIconImage(new ImageIcon(mainicon).getImage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我得到以下錯誤:
java.net.MalformedURLException: no protocol: icon.gif
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at com.mgflow58.Main.Game.main(Game.java:28)
文件icon.gif是在根文件夾,我甚至試圖將它複製到執行代碼的類所在的src/com/mgflow58/Main中。我做錯了什麼?無論我嘗試使用哪種方法,我都無法設置圖像圖標,而且我一直在努力尋找答案。