In Eclipse, when I run the code, this works:
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);
}
}
And here's the File Structure from my Package Explorer:
ShowImage (project)
> src / Main.java
> src / Action-exit-icon.png
Also, this workspace is located in Z:eclipse_projects
I can see the ImageIcon icon = new ImageIcon("src/Action-exit-icon.png"); is working nicely, and the menuBar does it's job.
Now let's Export this project, and I'll email the JAR to a friend of mine.
- Right-click project > Select Export
- Select Java > Runnable JAR File
- I choose the Main File in Launch configuration
- Export destination: my desktop
- Library handling: Extract required libraries into generated JAR
- go to my desktop, double-click the ShowImage.jar
The JFrame shows up, but the Action-exit-icon.png isn't appearing at all.
When I open the ShowImage.jar, to view it's contents, I see the Main.class, Action-exit-icon.png, META-INF.
Ok, I'm seriously confused about how to reference an image, or any resource now.
What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…