日期:2014-05-20  浏览次数:20989 次

关于Swing中重启功能的实现,还请高手支招。
最近在用Swing做一个重启功能,需要先System.exit(0)之后,再开启一个进程执行java程序。还请高手支招啊!谢谢!

------解决方案--------------------
之前有人问过类似的问题
http://topic.csdn.net/u/20110821/14/98449a61-0f28-4338-baea-ca908b850c58.html

class Test {
    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                Runtime.getRuntime().exec("java Test"); 
                //Test.main(new String[0]); //或者这样试试看
            }    
        });
        System.exit(0);
    }
}


------解决方案--------------------
我觉得楼主没有弄清楚 Runtime的 addShutdownHook 方法。

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
    public static void main(final String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable(){
                public void run(){
                    final JFrame frame = new JFrame("Main");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setPreferredSize(new Dimension(400,300));
                    final JButton restart = new JButton("Restart");
                    restart.addActionListener(new ActionListener(){
                            @Override public void actionPerformed(ActionEvent e){
                                Runtime.getRuntime().addShutdownHook(new Thread(){
                                        @Override public void run(){
                                            try {
                                                new ProcessBuilder("java","Main").start();
                                            } catch (IOException e) {
                                            }
                                        }
                                    });