简体   繁体   中英

close cmd + frame when click on the close button

hello i have a code that when runned opens cmd and then it opens the frame. i want the cmd to be closed as soon as the frame is opened or the cmd should be closed at the same moment as the user closes the frame. this is the code when i close my frame.

frame = new JFrame("BrainSla");
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

here is the main code:

public static void main(String args[]) {
    try {
        System.out.println("BrainSla - By Jannes Braet, Steven Brain, Wout Slabbinck.");
        nodeID = 10;
        portOff = 0;
        setHighMem();
        isMembers = true;
        signlink.storeid = 32;
        signlink.startpriv(InetAddress.getLocalHost());
        new Jframe(args);
        //instance = new client();
        //instance.createClientFrame(503, 765);
    } catch(Exception e) {
        e.printStackTrace();
    }
}

could someone tell me how i could do something like that ?

change frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); to

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This will exit the application as soon as you close the frame

If by 'cmd' you are referring to the 'command line' or CLI. Options:

  1. Launch it from a bat file (or similar per OS) using javaw instead of java
    • Low learning curve.
    • Not very professional look.
  2. Make it a runnable Jar (double click to open)
    • Medium learning curve.
    • Medium professional look.
  3. Launch it using JWS
    • High learning curve.
    • Very professional look.

If you run from a command line closing the command line window will close your application prematurely. Not sure of any way to do it on Windows but on Linux you can background the process and do it using the command:

nohup java -jar myprogram.jar & 

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092 ).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM