使用停止按钮停止无限循环 [英] stop infinite loop using stop button

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

问题描述

启动无限循环后,我无法关闭 JFrame.

After starting infinite loop, I am unable to close JFrame.

我想使用停止按钮停止无限循环.

I want to stop infinite loop using stop button.

我正在使用开始按钮开始无限循环.我想使用停止按钮关闭该循环.

I am starting an infinite loop using start button. I want close that loop using stop button.

  1. if(stop.getModel().isPressed()){break;} 不起作用

  1. if(stop.getModel().isPressed()){break;} is not working

actionListener 用于识别按钮点击并使用 break 语句终止 while 循环也不起作用

actionListener used to identify button click and using break statement to terminate while loop is also not working

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class NewClass1 {

private String arg = "";

public NewClass1() 
{

    JFrame frame = new JFrame("Datacolor software automate");

    JButton stop = new JButton("STOP");
    stop.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) 
        {
          arg = (String)ae.getActionCommand();  
          System.out.println(arg);
        }
    }); 

    JButton button = new JButton("Start");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {

        int i = 0;
        while (true)
        {
        try {

         System.out.println(i);
         i++;                 

         if(arg.equals("STOP"))
         {
             break;
         }

         } 
        catch (Exception e)
         {
         System.out.println(e.toString());
         }

         }


        }
    });

    frame.add(button);
    frame.add(stop);
    frame.setLayout(new FlowLayout()); 
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }

   public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() 
    {           
    new NewClass1();        
    }
    }); 


    }

    }

点击停止按钮时无限循环必须终止.使用开始按钮启动无限循环后,我无法使用 JFrame 中的任何按钮.

On clicking stop button infinite loop must terminate. I able not able to use any buttons in JFrame after starting infinite loop using start buttton.

推荐答案

一开始你不能点击停止"按钮,这是因为你运行了一个大任务(while(true) 部分代码)在 事件调度线程会导致整个 GUI 冻结.

You cannot click "Stop" button in the first place, and this is because you run a big task (the while(true) part of your code) in the Event Dispatch Thread which will cause your whole GUI to freeze.

为了避免这种情况并使其正常工作,您必须使用 SwingWorker. 一个允许您在后台运行长时间/繁重任务并(可选)在 GUI 中发布它们的类.

In order to avoid this, and make it work, you will have to use a SwingWorker. A class that allows you to run long/heavy tasks in the background and (optionally) publish them in GUI.

那么,如果你想取消这个 SwingWorker,调用它的 cancel() 方法就足够了.

Then, if you want to cancel this SwingWorker, a call to its cancel() method will be enough.

看看下面的例子:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class NewClass1 {
    private String arg = "";
    private SwingWorker<Void, Integer> worker;

    public NewClass1() {
        JFrame frame = new JFrame("Datacolor software automate");
        JButton stop = new JButton("STOP");
        stop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                worker.cancel(true);
            }
        });

        JButton button = new JButton("Start");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                initializeWorker();
                worker.execute();
            }
        });

        frame.add(button);
        frame.add(stop);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    private void initializeWorker() {
        worker = new SwingWorker<Void, Integer>() {

            @Override
            protected Void doInBackground() throws Exception {
                int i = 0;
                while (!isCancelled()) {
                    i++;
                    publish(i); // give this i to "process" method
                }
                return null;
            }

            @Override
            protected void process(List<Integer> chunks) {
                int i = chunks.get(0);
                System.out.println(i);
            }
        };
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new NewClass1());
    }

}

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

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