Thực sự muộn vào ngày này, nhưng hey, tốt hơn muộn hơn bao giờ hết. Sử dụng start() khi khởi tạo mọi thứ. Nếu bạn đang sử dụng JFrame, hãy sử dụng bắt đầu (khung Jframe) để nó tự động xử lý khi chương trình gần bằng tay. Nếu bạn không, hãy gọi onClose() khi chương trình của bạn được thoát thủ công nếu không chương trình sẽ không bắt đầu vào lần tiếp theo.
package your.package;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
public class ReLaunch {
private static boolean relaunchClose = false;
private static File runCheck = new File("run.check");
private static File deleteCheck = new File("delete.check");
/**
* Use ReLaunch to stop multiple instances
*/
public static void start() {
//Check to see if application is already running
if(runCheck.exists()) {
//Mark a request to exit the existing application
try { deleteCheck.createNewFile(); } catch (IOException e) { e.printStackTrace(); }
//Wait until the existing application terminates itself
while(runCheck.exists());
//Remove the delete request so current application doesn't terminate
if(deleteCheck.exists()) deleteCheck.delete();
}
//Mark that this application is currently running
try { runCheck.createNewFile(); } catch (IOException e) { e.printStackTrace(); }
//Creates a new thread that checks if a new application is requesting to run
new Thread(new Runnable() {
public void run() {
//Wait until delete request shows up
while(!deleteCheck.exists());
//Proof that the application is closed to be re-launched
relaunchClose = true;
//Unmarks this application as running
if(runCheck.exists()) runCheck.delete();
//Terminated so new application can run
System.exit(0);
}
}).start();
}
/**
* Same as start, but automatically handles when the frame is closed by the user by marking that no applications are running
* @param frame JFrame which needs to be closed
*/
public static void start(JFrame frame) {
start();
//Listen for when the window is manually closed
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
onClose();
}
});
}
/**
* Marks this application as not running if it is exited manually
*/
public static void onClose() {
if(!relaunchClose) runCheck.delete();
}
}
Có nút dừng với một hình ảnh hình vuông màu đỏ. Nhấp vào nó để dừng/giết ứng dụng. –
@LuiggiMendoza Điều đó chỉ dừng quy trình hiện tại. Bạn cần phải chấm dứt quá trình java thông qua trình quản lý tác vụ (ít nhất, đây là cách tôi đã luôn luôn thực hiện nó). Nhưng thẳng thắn, chỉ cần thêm một onclose vào cửa sổ của bạn: 'frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE)' – Vulcan
@Vulcan nó làm việc cho tôi ngay cả với các ứng dụng đa luồng mà tôi chạy trên Eclipse (nó thậm chí hoạt động để dừng/diệt máy chủ ứng dụng web)). –