单击按钮应在 Java 中停止整个应用程序(使用 Netbeans IDE)

Button Click Should Stop The Entire Application in Java (Using Netbeans IDE)

我在 Java 中有两个名为“connect”和“Disconnect”的按钮,当我单击 "connect" 按钮时,它将打开一个暂存文件。

我的问题是:

当我单击 "Disconnect" 按钮时,我的草稿文件也应该关闭。我该怎么做 ?请帮助我。

我添加了以下内容:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try { 

            Runtime r = Runtime.getRuntime();
            r.exec("C:\Program Files\Scratch 2\Scratch 2.exe C:\Users\Admin\Desktop\fwdbckpwm12.sb2");



        } catch (IOException ex) {
            Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      System.exit(0);
    } 

但是,这不会关闭我的暂存文件。

怎么样:

Runtime r = Runtime.getRuntime();
Process proc = r.exec("C:\Program Files\Scratch 2\Scratch 2.exe C:\Users\Admin\Desktop\fwdbckpwm12.sb2");

然后按下按钮时:

proc.destroy();

在必要时声明 proc 以使其工作。

编辑:这是对我有用的东西。

import javax.swing.*;
import java.io.IOException;

public class Main {
    static Process proc;

    public static void main(String[] args) {
        try {
            proc = Runtime.getRuntime().exec("Notepad.exe");
        }
        catch(IOException io) {

        }

        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame();
            JButton button = new JButton("Kill");
            frame.add(button);
            button.addActionListener(e -> {
                proc.destroyForcibly();
            });
            frame.pack();
            frame.setVisible(true);
        });
    }
}

注意 destroy 被 destroyForcibly 取代了。但对我来说,破坏也有效。也许这与您尝试 运行.

的 exe 文件有关