Search code examples
javajar

jar file doesn't do anything when executed (VSCode)


Here I have a short program, which I would like to export as a .jar file. When I use VSCode's "Export Jar..." option (and select Test as the main class), it creates the jar file without any errors, but when I run it (by double clicking), nothing happens. When I run the code from within VSCode however, it works as expected (the window shows up and says "Hello World"). Here's my code:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setSize(600, 400);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLocationRelativeTo(null);
                    frame.getContentPane().add(new JLabel("Hello World!"));
                    frame.setVisible(true);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Solution

  • If you want to run your java program (when it is compiled in a jar file) you need to do the following:

    java -cp your-jar-name.jar Test
    

    Test is a full name (including package name) of your class with main method.

    If Main-Class is defined in manifest your can do also this

    java -jar your-jar-name.jar
    

    Double click won't work if you click on jar file in some operating systems. You can use .sh script in Linux or .bat script in Windows and click on this script.