Some Java applications are distributed as Jar files, where the user can just double-click the file and 'Bang!' the application opens up. When you double click on a normal Jar file we just get a error message saying "Failed to load Main-Class...".
Follow the following steps to create an executable Jar:
- Create a simple Swing program which displays a label
- import javax.swing.*;
- import javax.swing.event.*;
- public class HelloWorldSwing {
- /**
- * Create the GUI and show it. For thread safety,
- * this method should be invoked from the
- * event-dispatching thread.
- */
- private static void createAndShowGUI() {
- //Make sure we have nice window decorations.
- JFrame.setDefaultLookAndFeelDecorated(true);
- //Create and set up the window.
- JFrame frame = new JFrame("HelloWorldSwing");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Add the ubiquitous "Hello World" label.
- JLabel label = new JLabel("Hello World");
- frame.getContentPane().add(label);
- //Display the window.
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- //Schedule a job for the event-dispatching thread:
- //creating and showing this application's GUI.
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- }
- Compile and run it and ensure that it works properly
- Create a file called "mainClass" with the following content in the same directory where you have the class file - if you have put the class inside a package create the file at the root of the package
Main-Class: HelloWorldSwing
Note the empty new line after the class name.
- From the directory run the following command from the command prompt to create a Jar file - "jar cmf mainClass HelloWorldSwing.jar *.class". This creates the executable Jar file. Here "m" refers to the manifest file - "mainClass"
- Now double click on the Jar file and see your swing application come to life!!
No comments:
Post a Comment