2
在Eclipse,當我運行的代碼,這個工程:加載圖標資源錯誤
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("test viewing images");
frame.setSize(600,300);
frame.setLocationRelativeTo(null); // centered on monitor
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/**
* Menu Bar stuff
*/
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
// MENU BAR
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
menuBar.setVisible(true);
// MENU 1
menu = new JMenu("File");
menuBar.add(menu);
// MENU 1 ITEM
ImageIcon icon = new ImageIcon("src/Action-exit-icon.png");
menuItem = new JMenuItem("Exit Program", icon);
menu.add(menuItem);
frame.setVisible(true);
}
}
下面是從我的包資源管理器的文件結構:
ShowImage (project)
> src/Main.java
> src/Action-exit-icon.png
此外,該工作區位於Z:\ eclipse_projects
我可以看到ImageIcon icon = new ImageIcon(「src/Action-exit-icon.png」);正在很好地工作,menuBar是它的工作。
現在讓我們導出這個項目,然後我將JAR發送給我的一位朋友。
- 右擊項目>選擇導出
- 選擇Java>運行的JAR文件
- 我選擇在啓動配置中的主文件
- 出口目的地:我的桌面
- 庫處理:提取需要的庫生成JAR
- 轉到我的桌面,雙擊ShowImage.jar
JFrame出現,但是Action-exit-icon.png根本沒有出現。
當我打開ShowImage.jar,查看它的內容時,我看到Main.class,Action-exit-icon.png,META-INF。
好吧,我對如何引用圖像或任何資源現在感到非常困惑。 我在做什麼錯?
我已經實際上已經嘗試過了,在Eclipse中,getClass()以紅色下劃線。如果我嘗試啓動它,我得到這個:「不能從類型Object靜態引用非靜態方法getClass()。 – coffeemonitor
我認爲,因爲你調用靜態/主要方法 –
它需要它上下文類加載器創建的一個對象的類,沒有一個J2SE類使用該加載器加載,而是像'Main userObj = new Main(); ..userObj.getClass()。getResource(「/ src/Action –