简体   繁体   中英

how to access a .png file from within a compiled netbeans project - java

I am fairly new to Java and I am trying to create a small dice game using NetBeans 7.4. I have created the game and it works fine, but I wished to run the program outside of running the project in the NetBeans IDE, so I created a Windows Batch file (.bat) to do the trick:

@ECHO OFF
java -jar "C:\Users\Admin2\My Documents\NetBeansProjects\yahtzee\dist\yahtzee.jar"

While this does work in executing the project (after I've built and compiled it of course), I noticed that all of my outside resources were missing - mainly the .png files I used to show the dice; they simply do not appear which is not a problem inside NetBeans. I have tried ImageIcon diceSideOne = new ImageIcon(this.getClass().getResource("src//images//d_1.png"); but it throws:

Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.(ImageIcon.java:205) at yahtzee.yahtzeeGUI.(yahtzeeGUI.java:17) at yahtzee.Yahtzee.main(Yahtzee.java:7)

Java Result: 1

I am almost certain I am using this.getClass().getResource() incorrectly, but I cannot find any useful information as to how to use it correctly. Can somebody please either help with my issue or send me in the right direction? Any help is greatly appreciated. The picture that I am trying to access is in C://Users//Admin2//My Documents//NetBeansProjects//yahtzee//src//images//d_1.png , if that is any help.

src will not exist once the application is compiled, in fact, you should never be referencing src ever, it's just not required.

NetBeans will bundle the contents of the src directory, excluding *.java (and *.form ), into the resulting .jar file, this includes your images

Instead, try using getClass().getResource("/images/d_1.png"); instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM