最後成功的方法是以下的寫法。
PS. 這裡我是用在 JFrame 的標題列圖示,以及通知區(System Tray)的圖示。
Java 檔路徑:/src/{package_name}/MainPanel.java
圖片檔路徑:/src/{package_name}/icon.png(即跟 MainPanel.java 是放在同一個目錄內)
標題列圖示的部份
1 2 3 4 5 6 |
// Get the Image String fileNameOfIcon = "icon.png" ; URL iconImage = this .getClass().getResource(fileNameOfIcon); // Set icon Image icon = Toolkit.getDefaultToolkit().getImage(iconImage); this .setIconImage(icon); |
1 2 3 4 5 6 |
// Get the Image String fileNameOfIcon = "icon.png" ; URL iconImage = this .getClass().getResource(fileNameOfIcon); // Set icon ImageIcon imageIcon = new ImageIcon(iconImage, "Notification icon" ); TrayIcon trayIcon = new TrayIcon(imageIcon.getImage()); |
參考資料:
1、How to correctly get image from 'Resources' folder in NetBeans
2、Debugging getResource*
3、How to access a Image file in a Eclipse Project Folder
沒有留言:
張貼留言