How do I make my java application open a console/terminal window?

I found this while looking for an answer myself, I ended up writing this bit:

/**
 * This opens a command line and runs some other class in the jar
 * @author Brandon Barajas
 */
import java.io.*;
import java.awt.GraphicsEnvironment;
import java.net.URISyntaxException;
public class Main{
    public static void main (String [] args) throws IOException, InterruptedException, URISyntaxException{
        Console console = System.console();
        if(console == null && !GraphicsEnvironment.isHeadless()){
            String filename = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
            Runtime.getRuntime().exec(new String[]{"cmd","/c","start","cmd","/k","java -jar \"" + filename + "\""});
        }else{
            THEMAINCLASSNAMEGOESHERE.main(new String[0]);
            System.out.println("Program has ended, please type 'exit' to close the console");
        }
    }
}

not sure if my answer is still relevant, but feel free to use it with the comment kept in o/

Only flaw I can think of is that it leaves the cmd window open after the program completes.

Usage: place this class in the same package as your main class and set it as the main class, it will open a command prompt window if one is not open, or if one is open launch the main class. Name / location of jar file is automatic. Designed for windows, but if you want it for another system just message me and I'll fix it. (I could do OS detection but I'm lazy and just making this so I can turn in a double-click jar file to my professor who uses windows).


If you want full control, you can implement a Console window in Swing which does what you have now.

If you cannot open said window (if headless) or the user asks for it on the command line, then just default to your current behaviour.


Double-clicking a jar opens it with whatever application you've associated to it in your OS. By default, javaw[.exe] is normally associated to jar files. That's the binary that runs without a terminal window. To see a terminal on double-click, you'd need to associate the java[.exe] binary with jar files.