How to make the program restart on pressing the [Java] button


How to make the program restart when you press JButton the program closes and automatically opens?


You can use this only as a last resort. In my case, it was the impossibility of killing the static, inside the addiction.

There is one way, it is not stable for a number of reasons, it has drawbacks, but I used it and in a predictable environment it has worked and still works to this day.

The point is to start a new instance of jvm with the same arguments as the current instance you want to restart, and immediately shutdown the current instance.

  1. Create a bat or sh file to run the application.

  2. Bind the launch of this file via Runtime.exec () to the button and then exit your program.

Of course, you can refine the method and find and run the required jvm from the code, but I didn't need it and I didn't.

The big drawback of this method is that it won't work in ide, or you still need to figure out how to make it work in ide, if you suddenly need it.

I stopped at runtime.

PS I put together an example that works from ide (I have an idea), I suggest to finish it to mind already in place =) here you can refine it for a long time, throw jvm arguments, for example, take into account the launch from jar and similar cases, the general principle remains the same.

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;

public class Restart {

    public static final String Q = "\"";

    public static void main(String[] args) {
        JButton button = new JButton("close");
        button.addActionListener(evt -> {
            try {
                Class<?> clazz = Restart.class;
                String classPath = clazz.getProtectionDomain().getCodeSource()
                String javaHome = System.getProperty("java.home");
                String cmd = Q + javaHome  + "/bin/java" + Q
                        + " -cp " + Q + classPath + Q
                        + " " + clazz.getSimpleName();
                System.out.println("cmd = " + cmd);
            } catch (Exception e) {
                System.out.println("cannot restart");
        JFrame frame = new JFrame("restart jvm");
        frame.setLayout(new BorderLayout());
        frame.add(button, BorderLayout.SOUTH);
        frame.setSize(new Dimension(300,100));
Scroll to Top