简体   繁体   中英

Create executable JAR from classes and images using Eclipse

I have the following folder:

Game Of Life
|_bin
| |_Board.class
| |_Frame.class (main class)
|   ...
|_res
| |_playToolbar.png
| |_pauseToolbar.png
|   ...
|_src
  |_Board.java
  |_Frame.java
    ...

How do I create an executable .jar containing every class and image, so that when I execute the .jar it runs the Frame class? I am using Eclipse.

If you are using eclipse, you can do a Rightclick->Export on the project and select Runnable Jar File under Java . Your res folder has to be configured as a source Folder in eclipse, otherwise it wont be exported.

You also have to regard that Loading the images may be different once they are packed in a jar file. See this for more information

I think it is best to put your pictures inside a package. This way, everything will be packaged and loaded from your JAR file.

Afterward you will have to load your images using the getResource(...) method from an instance of Class.

You will have something like this:

GameOfLife
|- src
|  |- my
|  |  |- company
|  |  |  |- app
|  |  |  |  | Board.java
|  |  |  |  | Frame.java
|  |  |  |  |- resources
|  |  |  |  |  |- playToolbar.png
|  |  |  |  |  |- pauseToolbar.png

Then to create an ImageIcon of "playToolbar.png" from the Frame class you will have to use:

new ImageIcon(Frame.class.getResource("resources/playToolbar.png"));

Or:

new ImageIcon(Frame.class.getResource("/my/company/app/resources/playToolbar.png"));

If you are using Netbeans GUI builder, it can load resources from package without any problem.

To autorun your Frame class you have to create a MANIFEST.MF file and put it inside a folder named META-INF at the root of your JAR. Inside, you can define Frame as the Main-Class:

Manifest-Version: 1.0
Main-Class: my.company.app.Frame

Eclipse can do this step automatically if you select export->Runnable Jar.

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