public void init() {
// 取得資源相對路徑(Java 使用絕對路徑尋找資源,打包成 jar 時資源會找不到)
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("a.gif"));
ImageIcon icon = new ImageIcon(image);
bt.setIcon(icon);
String cName = this.getClass().getName();
System.out.println(cName);
this.add(bt);
this.setSize(300, 300);
setVisible(true);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
關鍵在於使用 getClass().getResource("a.gif") 取得相對路徑資源,避免打包成 JAR 後因絕對路徑失效導致資源載入失敗。