如何用按钮停止循环? [英] How to stop a loop with a button?

查看:230
本文介绍了如何用按钮停止循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,当单击开始按钮时会启动循环,我想用停止按钮停止它。问题是循环启动按钮在循环完成之前不起作用。
我搜索了类似的问题并理解问题是循环是在actionPerformed但我无法设法在actionPerformed之外采取循环。
我已经尝试过制作一个新的课程并打电话给它,但完全相同的事情发生了。
顺便说一下,我是Java的初学者也是stackoverflow,如果我做错了,我很抱歉。

只需代码:

I am writing a program which starts a loop when start button is clicked and I want to stop it with a stop button. Problem is when loop starts buttons do not work until loop is complete. I've searched similar questions and understood the problem is loop is in actionPerformed but I couldn't manage to take the loop outside of the actionPerformed. I've tried that to make a new class and call for it etc but exactly same thing happened. By the way I am a beginner at Java also stackoverflow and I am sorry if I did something wrong.
simply code:

OtherClass obj;
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == startButton) {
    while(true) {
        obj = new OtherClass();
        obj.doJob();
    }
    else if(e.getSource() == stopButton) {
    obj.stopLoop();
    }
}

public class OtherClass  {
    private boolean isStopped = false;
    public OtherClass() {
    }
    public void doJob(){
        while(true) {
            //loop...
            if(isStopped) {
                break;
            }
        }
    }


推荐答案

您需要在单独的线程(也称为工作线程)中运行doJob()。按下按钮时启动线程,再次按下时,将isStopped标志设置为true。注意不要在工作线程中执行UI操作(例如更新进度条) - 需要调用特殊方法来从工作线程更新UI。

You need to run doJob() in a separate thread (also called a "Worker thread"). Start the thread when the button is pressed and set the isStopped flag to true when it is pressed again. Be careful not to execute UI actions in the worker thread (such as updating progress bars) - there are special methods you need to call to update the UI from the worker thread.

由于这是一个非常普遍的问题(我的答案也非常普遍),我建议在Google上注意AWT ui thread,Worker thread和Java threading。

Since this is a very general question (any my answer is very general too), I suggest to look out for "AWT ui thread", "Worker thread" and "Java threading" in general on Google.

一个很好的起点可以是课程: Swing中的并发

A good starting point could be Lesson: Concurrency in Swing

这篇关于如何用按钮停止循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆