2015-02-11 77 views
3

我遇到了將我的java文件導出到可運行jar文件的問題。 在eclipse中它工作正常,但是當我導出它時,它不起作用。在Eclipse上工作但在導出到可運行jar文件時不工作的Java項目

我已經嘗試過(Java的罐子MyJar.jar)來獲取日誌,但它說 「Unnable訪問的jar文件」

我認爲這個問題是因爲這一點:

java.net.URL logoOneUrl = getClass().getResource("/logo.png"); //already tried without the "/" and it doesn't work withouth the "/" 
Icon logoOne = new ImageIcon(logoOneUrl) 

因爲當我把它放在評論//當我導出它運行,但沒有圖像。

我也試過這種方式: java.net.URL logoScience = getClassLoader().getResource("logo.png");但它不起作用。 我在做什麼錯? 如何導出JLabel上帶有圖像的可運行jar文件?

(這就是我對我的JLabel) JLabel lblImgLogin = new JLabel(logoOne);

UPDATE

ImageIcon icon = createImageIcon("/logo.png","a pretty but meaningless splat");

protected ImageIcon createImageIcon(String path,String description) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); } return null; }

JLabel lblImgLogin = new JLabel(icon);

同樣的問題,廠在食,但在出口時要運行的JAR文件無法正常工作

+0

該文件位於您的項目中? – 2015-02-11 11:04:37

+1

「無法訪問jar文件」與代碼無關。它與當前目錄中不存在jar文件MyJar.jar的事實有關。 – 2015-02-11 11:05:26

+0

@JBNizet但爲什麼它的工作,然後,如果他評論的形象? – 2015-02-11 11:07:34

回答

4

這是正確的:

enter image description here

public class MainApp { 

    public static void main(String[] args) { 
     JFrame frame = new JFrame("Testing"); 
     ImageIcon icon = createImageIcon("/resources/logo.png"); 
     JLabel label1 = new JLabel("Image and Text", icon, JLabel.CENTER); 

     //Set the position of the text, relative to the icon: 
     label1.setVerticalTextPosition(JLabel.BOTTOM); 
     label1.setHorizontalTextPosition(JLabel.CENTER); 

     frame.getContentPane().add(label1); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    protected static ImageIcon createImageIcon(String path) { 
     URL imgURL = MainApp.class.getResource(path); 
     if (imgURL != null) { 
      return new ImageIcon(imgURL); 
     } else { 
      System.err.println("Couldn't find file: " + path); 
      return null; 
     } 
    } 
} 

enter image description here

enter image description here

+0

http://i.imgur.com/TSQYzwI.png?1 – Firmeza 2015-02-11 11:53:50

+0

第一個問題是,在圖像前留一個斜槓。使其成爲「/圖像/標誌。png「,而不是」images/logo.png「,其次,更好地使用」Resources「文件夾中的圖像 – 2015-02-11 12:05:21

+0

@SaqibRezwan你回答和評論的內容,根本沒有任何作用 – Firmeza 2015-02-11 12:14:43

1

創建一個文件夾名 '資源'(正是這個名字)。現在將Logo.png保存在Resources文件夾中。現在使用代碼如下。編譯並生成jar(使用'生成的jar包需要的庫'用於Eclipse導出)。如果在提取jar之後,你會得到Resources文件夾和它下面的文件,然後希望它能起作用。對不起,我的英文不好

+0

顯示java.lang.NullPointerException \t在javax.swing.ImageIcon中。(來源不明) 好好嘗試編譯/運行 – Firmeza 2015-02-11 11:51:26

+0

的路徑是不正確的地方。你創建了Resources文件夾嗎?它只是在項目路徑中嗎?如果路徑是rig它應該工作。我遇到了這個問題並應用了上述過程。你能否給出png文件的項目結構? – 2015-02-11 11:56:32

+0

http://i.imgur.com/ZLCf0XL.png – Firmeza 2015-02-11 12:04:31

相關問題