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);
    }
}
相关推荐
键盘会跳舞8 分钟前
【C++多线程】死锁诊断工具实战:从 Windows 到 Linux 的全链路排查
linux·c++·windows·死锁
吴声子夜歌11 分钟前
Java扩展——OkHttp
java·开发语言·okhttp
卓怡学长18 分钟前
w210基于springboot反诈平台设计与实现
java·spring boot·spring·intellij-idea
萧瑟余晖27 分钟前
Java深入解析篇六十一之编译器API(javax.tools)详解
java·开发语言
码云数智-园园1 小时前
C++ STL 容器怎么选?vector、list、map、unordered_map 优缺点对比
java·开发语言
en.en..1 小时前
竖线 |:管道、按位或、掩码组合
java·开发语言
程序猿乐锅2 小时前
【计算机组成原理 | 第六章】中央处理器 CPU
java·开发语言
大模型丫丫2 小时前
如何提升单体 Spring Boot 应用的并发数?
java·spring boot·后端
Terra.K2 小时前
ThreadLocal解决一个线程里面跨层传递问题
java·开发语言·后端
泡海椒2 小时前
低代码规则开发:JQuick-Java声明式配置驱动开发落地教程
java·低代码·rxjava