javafx-启动main时获取pid,关闭windows窗口时杀掉pid

有时候发现,关掉了窗口,但是发现进程列表里面还有这个进程,因此在关闭的时候在kill一次代码可以参考

java 复制代码
package sample.main;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.IOException;
import java.lang.management.ManagementFactory;

public class allManager extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{

        Parent root = null;
        FXMLLoader loader = new FXMLLoader();

        try {
            loader.setLocation(getClass().getResource("/allManager.fxml"));
            root = loader.load();
//            primaryStage.initModality(Modality.WINDOW_MODAL);

            Scene scene = null;
            scene = new Scene(root, 600, 400);

            String name = ManagementFactory.getRuntimeMXBean().getName();
            System.out.println(name);
            String pid = name.split("@")[0];
            System.out.println("Pid is:" + pid);

            primaryStage.getIcons().add(new Image("/uncleW.jpeg"));
            primaryStage.setTitle("allManager ="+pid);
            primaryStage.setScene(scene);

            primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    try {
                        // 使用Runtime类执行taskkill命令
                        Runtime.getRuntime().exec("taskkill /PID " + pid + " /F");
                        System.out.println("进程已被杀死");
                    } catch (IOException e) {
                        System.out.println("杀死进程失败: " + e.getMessage());
                    }
                }
            });

            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
        launch(args);
    }
}
相关推荐
蜗牛^^O^28 分钟前
Docker和K8S
java·docker·kubernetes
从心归零1 小时前
sshj使用代理连接服务器
java·服务器·sshj
指间and流年1 小时前
Windows Server2016多用户登录破解
windows
IT毕设梦工厂2 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius3 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
七夜zippoe3 小时前
分布式系统实战经验
java·分布式
是梦终空3 小时前
JAVA毕业设计176—基于Java+Springboot+vue3的交通旅游订票管理系统(源代码+数据库)
java·spring boot·vue·毕业设计·课程设计·源代码·交通订票
落落落sss3 小时前
sharding-jdbc分库分表
android·java·开发语言·数据库·servlet·oracle
码爸3 小时前
flink doris批量sink
java·前端·flink
Monodye4 小时前
【Java】网络编程:TCP_IP协议详解(IP协议数据报文及如何解决IPv4不够的状况)
java·网络·数据结构·算法·系统架构