简体   繁体   中英

NetBeans-made jar file won't work

So I made this (very simple) program with a swing GUI with NetBeans, and I clicked build to make a jar file. When I run it by double clicking it, it tells me it could not find the main class, which, after checking, I am sure is definitely there. But, when I run it from Command Prompt, it works perfectly. Any easily-determinable reason for this strange behaviour (if you want the source code, I can post it here)?

The things that seem to be needed in NetBeans are:

  • The project has to be the Main Project (by right clicking on it in the Projects list).
  • You have to set the Main Class in the project properties. (Right click, Properties, Run, Main Class.)

Then when you right click on your project and do a "Clean and Build", a jar will get built into the dist subdirectory.

If that fails to fix the problem, here's a longer story...

When you double click a jar file to run it, the operating system acts as if you had typed this from the command line:

java -jar filename.jar

(When you say it works for you from the command line, is this what you're typing?)

At that point, the Java executable looks for a file inside the jar named META-INF/MANIFEST.MF . And then in the contents of that file, it looks for the value of a property, Main-Class . And finally it looks for the class of that name in your jar and runs its static main(String[]) method.

So if your jar is failing to run, you can do the following to debug what's going on:

  • Clean and rebuild your project in NetBeans.
  • Double check that your class(es) are actually in the jar:
    • Start a command prompt
    • cd into the dist subdirectory of your project.
    • Use a command like jar tf filename.jar to list what's in there.
  • Double check that the MANIFEST.MF file is correct:
    • Again in a command prompt
    • cd into the dist directory.
    • Use a command like jar xf filename.jar META-INF/MANIFEST.MF to extract the manifest.
    • Look at the contents of that file (eg type META-INF\\MANIFEST.MF ) and make sure Main-Class is set to the appropriate class.

If all of the above check out, then double clicking the file should work.

您是否将包含项目设置为“主项目”?

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