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);
    }
}
相关推荐
Deng87234734831 分钟前
代码语法检查工具
linux·服务器·windows
开心香辣派小星1 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn2 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
摆烂z2 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea2 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の2 小时前
Spring Core常见错误及解决方案
java·后端·spring
奶油松果2 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis
霍夫曼3 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn08953 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu3 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter