Question:
How to make the program restart when you press JButton the program closes and automatically opens?
Answer:
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.
-
Create a bat or sh file to run the application.
-
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()
.getLocation().toString().split("file:/")[1];
String javaHome = System.getProperty("java.home");
String cmd = Q + javaHome + "/bin/java" + Q
+ " -cp " + Q + classPath + Q
+ " " + clazz.getSimpleName();
System.out.println("cmd = " + cmd);
Runtime.getRuntime().exec(cmd);
System.exit(0);
} catch (Exception e) {
System.out.println("cannot restart");
}
});
JFrame frame = new JFrame("restart jvm");
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300,100));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}