views:

337

answers:

2

Possible Duplicate:
Is there a way to the hide win32 launch console from a Java program (if possible without JNI)

When I run my java swing application in a batch file on windows, the console/command window remains open whilst my java application is running. This creates an extra window on my taskbar which I would prefer not to have. But when I close the command window it stops my java application. Is there a way, perhaps via the batch file or command line parameters or code changes to my application, to have java.exe exit after bringing up my swing app and the console window close whilst my application still runs?

Main method is as follows:

public static void main(String args[]) {

    ApplContext applContext = new ApplContext();
    Throwable error = null;

    try {
        applContext.setUserConfigDir(args.length>0 ? args[0] : null);
        applContext.loadData();
        ApplTools.initLookAndFeel(Parameters.P_NIMBUS_LAF.of(applContext.getParameters()));
    } catch (Throwable e) {
        error = e;
    }

    // JWorkSheet is a JFrame.
    new JWorkSheet(applContext, error).setVisible();
}
+1  A: 

Ideally what you will eventually do somewhere in your code is call SwingUtilities.invokeLater(Runnable r). That will throw your GUI code into the correct thread, and you should be able to close the command line after the main thread exits.

This is a basic example of what I am talking about:

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            JFrame yourWindow = new YourFrame();
            yourWindow.createAndShow();
        }
    }
}
jjnguy
While this is the correct way to initialize a Swing UI, the console will not go away when the main thread exits. It will remain until java.exe exits which is when the last non-daemon thread in the process exits.
Dave Ray
You can close a console window after the main thread exits. It is a different way around the problem of having a different window I guess.
jjnguy
+4  A: 

Run your application with javaw.exe rather than java. If you're running from a bat file, use this in combination with the start command:

> start javaw.exe -jar myapp.jar

When run in this mode, it's a good idea to set up proper logging or at least redirect your output streams if you rely on the console for any debugging. For example, with no console, you'll never see those friendly stack traces printed for unhandled exceptions.

Note: java.exe is a Windows console application. As such, no matter how it is started, or what threads are running in it, a console will be allocated for it. This is the reason that javaw.exe exists.

Dave Ray
The GUI should never be coupled with the main thread in the first place.
jjnguy
I totally agree, but whether the UI is initialized in the main thread or the UI thread has no bearing on whether a console is constructed and maintained for the Java process.
Dave Ray