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);
    }
}
相关推荐
浩浩测试一下4 小时前
汇编 16位32位64位通用寄存器(逆向分析)
汇编·windows·stm32·单片机·嵌入式硬件·逆向·二进制
Java面试题总结5 小时前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
苦逼的猿宝5 小时前
学生心理咨询评估系统
java·毕业设计·springboot·计算机毕业设计
隔窗听雨眠5 小时前
doctype、charset、meta如何控制整个渲染流水线
java·服务器·前端
西安邮电大学7 小时前
SpringBean完整生命周期
java·spring
刀法如飞7 小时前
DDD 与 Ontology 对比分析:哪一种更适合AI时代复杂系统构建?
java·架构·领域驱动设计
SunnyDays10117 小时前
Java 读写 Excel 公式:从基础到高级的实战总结
java·开发语言·excel
wb043072017 小时前
Java 26
java·开发语言
白露与泡影7 小时前
JVM GC调优实战:从线上频繁Full GC到RT降低80%的全过程
java·开发语言·jvm
范什么特西7 小时前
Spring 动态代理 静态代理
java·后端·spring