我愿意在我的应用程序中添加一个按钮,单击该按钮将重新启动应用程序。我搜索了谷歌,但没有找到任何有用的东西,除了 this one 。但这里遵循的过程违反了 Java 的 WORA 概念。
还有其他以 Java 为中心的方法来实现此功能吗?是否可以只 fork 另一个副本然后退出?
提前致谢。感谢您的帮助。
@deporter 我已经尝试过你的解决方案,但它不起作用:(
@mKorbel 我通过采用您在 so 中显示的概念编写了以下代码
JMenuItem jMenuItem = new JMenuItem("JYM");
jMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
ScheduledFuture<?> future = executor.schedule(new Runnable() {
@Override
public void run() {
try {
Process p = Runtime.getRuntime().exec("cmd /c start java -jar D:\\MovieLibrary.jar");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}, 2, TimeUnit.SECONDS);
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
还有:
ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(2);
Callable<Process> callable = new Callable<Process>() {
@Override
public Process call() throws Exception {
Process p = Runtime.getRuntime().exec("cmd /c start java -jar D:\\MovieLibrary.jar");
return p;
}
};
FutureTask<Process> futureTask = new FutureTask<Process>(callable);
schedulerExecutor.submit(futureTask);
schedulerExecutor.shutdown();
try {
schedulerExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
它可以工作,但只能工作一次。如果我第一次启动应用程序并按 JYM 菜单项,那么它会关闭,几秒钟后它会使用 cmd 打开一个新的 ui,但如果我按该 JYM 菜单项,应用程序将完全终止,即,它不再再次启动。
非常感谢您的帮助。
已解决。
最佳答案
解决办法:
从 ActionListener 调用以下代码。
ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(2);
Callable<Process> callable = new Callable<Process>() {
@Override
public Process call() throws Exception {
Process p = Runtime.getRuntime().exec("cmd /c start /b java -jar D:\\MovieLibrary.jar");
return p;
}
};
FutureTask<Process> futureTask = new FutureTask<Process>(callable);
schedulerExecutor.submit(futureTask);
System.exit(0);
谢谢。
关于java - 重新启动 Swing 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9390481/