java - 如何在 JFrame 退出时运行终止命令?

标签 java multithreading swing

我知道尝试编写终止线程的代码背后的基础知识,但我遇到了一些问题。

我在 JFrame GUI 中有一个 JButton,它可以启动我正在尝试设置动画的模拟。它在 JButton 的 ActionPerformed 代码中调用

new AnswerWorker().execute();

AnswerWorker 类又扩展了 SwingWorker,以便可以在 GUI 仍处于 Activity 状态时绘制动画帧。

public class AnswerWorker extends SwingWorker<String, Integer> {
    protected String doInBackground() throws Exception
    {
        Threading threading = new Threading();
    return null;
    }
protected void done()
{
try {
    JOptionPane.showMessageDialog(InputGUI.this, AMEC.unsuccesfulpercentage + "% of iterations had trucks that had to sleep over");
    AMEC.unsuccesfulpercentage = 0;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}

}

为了创建一种停止模拟线程的方法,我创建了 Threading 类,它调用运行模拟的函数。

public class Threading extends Thread {

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
    try {
        AMEC.runsimulation();
    } catch (IOException ex) {
        Logger.getLogger(InputGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(InputGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
        }
    return;
    }
}

现在,在 runningsimulation() 函数中,我初始化一个 JFrame,并且如果通过单击其关闭按钮关闭 JFrame,我想终止运行模拟的线程。我该怎么做?

编辑:以上所有代码都在包含我所有 GUI 元素的文件 InputGUI.java 中调用。 runsimulation 函数位于我的主项目文件 AMEC.java

最佳答案

您可以重写 JFrame 上的 dispose() 方法以包含停止线程的调用

@Override
dispose(){
   stopThread();
   super.dispose();
}

关于java - 如何在 JFrame 退出时运行终止命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111671/

相关文章:

java - 从库模块导入特定风格

java - Swing JPanel - 绘制的图形复制而不是移动

java - PrinterJob 存档 tif 或 tiff

Java错误: cannot find symbol,并且无法找出原因

java - 使用 Spring Boot 和 WebSphere 8.5.5 进行远程 EJB 查找

ios - 在 iOS 的后台线程中绘图

java - 未能成功演示并发递增/递减

multithreading - 同一个进程的多个线程可以在多处理器系统中的不同处理器上运行吗?

java - java中绘制点

java - 如何使用 JPA 调用 firebird 可选择存储过程?