Jessica MC Jessica MC - 7 months ago 57
Java Question

How to print a message when a user closes Windows calculator?

I have a program in java. The program opens Windows calculator with Runtime.exec. So far so good, but I need that when program is closed by a user, a message appears saying "Program has been closed successfully".

I make it with destroy() but that isn't what I need.


You have to call waitFor() on the Process return by exec(). This will wait for the thread to end, and will return the exit value that you can test (0 is a successful exit value, everything else is an unsuccessful exit value).

try {
    final Process calc = Runtime.getRuntime().exec("calc");
    if (calc.waitFor() == 0) {
        JOptionPane.showMessageDialog(null, "Program has been closed successfully.", "Program closed", JOptionPane.INFORMATION_MESSAGE);
    } else {
        JOptionPane.showMessageDialog(null, "Program has been closed unsuccessfully.", "Program closed", JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
    JOptionPane.showMessageDialog(null, "IO error: " + e.getMessage(), "Exception encountered", JOptionPane.ERROR_MESSAGE);
} catch (InterruptedException e) {
    JOptionPane.showMessageDialog(null, "Thread interrupted: " + e.getMessage(), "Exception encountered", JOptionPane.ERROR_MESSAGE);