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

前端 未结 13 1364
日久生厌
日久生厌 2020-12-28 21:12

Is there any way I can make an executable .jar that will open up the command line when double clicked?

I\'m making a text-based adventure game. As of right now it is

13条回答
  •  情话喂你
    2020-12-28 21:53

    So this is my solution, I used the code from @Brandon Barajas and modified it. It creates a batchfile that starts the program by itself.

    public static void main(String[] args){
        Console console = System.console();
        if(console == null && !GraphicsEnvironment.isHeadless()) {
            String filename = YOURMAINCALSS.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
            try {
                File batch = new File("Launcher.bat");
                if(!batch.exists()){
                    batch.createNewFile();
                    PrintWriter writer = new PrintWriter(batch);
                    writer.println("@echo off");
                    writer.println("java -jar "+filename);
                    writer.println("exit");
                    writer.flush();
                }
                Runtime.getRuntime().exec("cmd /c start \"\" "+batch.getPath());
            } catch(IOException e) {
                e.printStackTrace();
            }
        } else {
            //your program code...
        }
    }
    

    If you want you can add a writer.println("pause"); before the "exit" print, to keep the window open after the progam finishes. Then you need to hit ENTER to close the window.

提交回复
热议问题