-1

I will develop a small App with Java / JavaFX to shutdown my mac with one click.

Here is my setonaction, windows ist working but not linux or mac os. Maybe someone have a idea. Thanks

button1.setOnAction(new EventHandler<ActionEvent>() {

            String commandEx = " ";

            @Override
            public void handle(ActionEvent event) {

                if (os.contains("Windows")) {
                    commandEx = "shutdown -s -t 10";
                } else if (os.contains("Linux")) {
                    commandEx = "shutdown -h now";
                } else if (os.contains("Mac OS X")) {
                    commandEx = "shutdown -h now";
                    try {
                        Runtime.getRuntime().exec(commandEx);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
code
  • 33
  • 5

1 Answers1

3

You can make use of this code

public static void main(String arg[]) throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 0");
    System.exit(0);
}

For system specific , you can use compare the operating sytem and then try different commands with root permission

public static void shutdown() throws RuntimeException, IOException {
    String shutdownCommand;
    String operatingSystem = System.getProperty("os.name");

    if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) {
        shutdownCommand = "shutdown -h now";
    }
    else if ("Windows".equals(operatingSystem)) {
        shutdownCommand = "shutdown.exe -s -t 0";
    }
    else {
        throw new RuntimeException("Unsupported operating system.");
    }

    Runtime.getRuntime().exec(shutdownCommand);
    System.exit(0);
}
bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • Mac OS `shutdown` requires `shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k] time [warning-message ...]` ... don't see a `t` property – MadProgrammer Sep 19 '17 at 23:27
  • 3
    It's still not likely to work (at least on the Mac) as it requires root access, so now you'd need to use `sudo` and figure out how to prompt the user for the root password, pass that to the process and deal with incorrect passwords - it's way more complicated then just calling the command – MadProgrammer Sep 19 '17 at 23:31
  • How about running the program itself in sudo mode? – bigbounty Sep 20 '17 at 02:35
  • Yeah, because giving root access to a program is always a good idea – MadProgrammer Sep 20 '17 at 02:45
  • @bigbounty thanks for your code Example. But you have to check for the password. – code Sep 20 '17 at 22:39