Friday, 14 July 2017

Executable jar file in java ~ java help

How to make an executable jar file in Java

The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.


Creating manifest file

To create manifest file, you need to write Main-Class, then colon, then space, then classname then enter. For example:
myfile.mf
  1. Main-Class: First  
As you can see, the mf file starts with Main-Class colon space class name. Here, class name is First.

In mf file, new line is must after the class name.



Creating executable jar file using jar tool

The jar tool provides many switches, some of them are as follows:
  1. -c creates new archive file
  2. -v generates verbose output. It displays the included or extracted resource on the standard output.
  3. -m includes manifest information from the given mf file.
  4. -f specifies the archive file name
  5. -x extracts files from the archive file
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given below:
  1. jar -cvmf myfile.mf myjar.jar First.class  
It is shown in the image given below:
creating executable jar
Now it will create the executable jar file. If you double click on it, it will call the main method of the First class.

We are assuming that you have created any window based application using AWT or SWING. If you don't, you can use the code given below:
First.java
  1. import javax.swing.*;    
  2. public class First{    
  3. First(){    
  4. JFrame f=new JFrame();    
  5.                     
  6. JButton b=new JButton("click");    
  7. b.setBounds(130,100,10040);    
  8.         
  9. f.add(b);    
  10.             
  11. f.setSize(300,400);    
  12. f.setLayout(null);    
  13. f.setVisible(true);    
  14.             
  15. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
  16. }    
  17. public static void main(String[] args) {    
  18.     new First();    
  19. }    
  20. }    

Let's see how executable jar file looks by the image given below:
executable jar file in java

No comments:

Post a Comment