问题描述
我愿意在我的应用程序中添加一个按钮,单击该按钮将重新启动应用程序。我搜索了谷歌,但除了之外没有找到任何帮助。但是这里遵循的程序违反了WORA的Java概念。
I am willing to add a button in my application which on-click will restart the app. I searched Google but found nothing helpful except this one. But the procedure follows here is violating the WORA concept of Java.
是否还有其他以Java为中心的方法来实现此功能?是否可以只分叉另一个副本然后退出?
Is there any other Java centric way to achieve this feature? Is it possible to just fork another copy and then exit?
提前致谢。感谢您的帮助。
Thanks in advance. I appreciate your help.
@deporter我已经尝试过您的解决方案,但它无法正常工作:(
@deporter I have tried your solution but it is not working :(
@mKorbel我通过采用
@mKorbel I wrote the following code by taking concept you had shown in 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 menuitem然后关闭,几秒后它会打开一个带有cmd的新UI,但是如果我按下JYM menuitem,应用程序将完全终止,即它不会再次启动。
its working but only once. If I launch the application for first time and press JYM menuitem then it shutdowns and after few second it opens a new ui with cmd, but if I press that JYM menuitem the application terminate completely, i.e., it is not again launches anymore.
我非常感谢你的帮助。
它已经解决。
推荐答案
解决方案:
从ActionListener调用以下代码。
Call the following code from the 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);
谢谢。
这篇关于重启Swing应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!