首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2SE

淺析 J2SE 專案資源路徑問題與解決方案

     編輯:J2SE
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 後因絕對路徑失效導致資源載入失敗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved