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);
    }
}
相关推荐
大飞哥~BigFei18 小时前
RabbitMq消费消息遇到的坑
java·rabbitmq·java-rabbitmq
隐形喷火龙18 小时前
Springboot集成OnlyOffice
java·spring boot·后端
5pace18 小时前
【SSM|第一篇】MyBatisPlus
java·spring boot·后端·mybatis
q***062918 小时前
如何在 Windows 上安装 MySQL(保姆级教程2024版)
数据库·windows·mysql
JosieBook19 小时前
【SpringBoot】37 核心功能 - 高级特性- Spring Boot 中的 自定义 Starter 完整教程
java·spring boot·后端
小二·19 小时前
Elasticsearch 面试题精编(26题|含答案|分类整理)
java·大数据·elasticsearch
BD_Marathon19 小时前
在 Linux 环境中配置 Eclipse 以开发 Hadoop 应用
java·hadoop·eclipse
草莓熊Lotso19 小时前
C++ 二叉搜索树(BST)完全指南:从概念原理、核心操作到底层实现
java·运维·开发语言·c++·人工智能·经验分享·c++进阶
oliveira-time19 小时前
单例模式中的饿汉式
java·开发语言