java - 使用按钮停止和开始循环

标签 java swing button while-loop

我正在尝试控制程序中的 while 循环以根据用户输入停止和启动。我已经用一个按钮尝试了这个,它的“开始”部分起作用了,但是代码进入了一个无限循环,如果不手动终止它我就无法停止。以下是我的全部代码: 标题类

package test;

    import javax.swing.JFrame;

    public class headerClass {
        public static void main (String[] args){
            frameClass frame = new frameClass();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(150,75);
            frame.setVisible(true);
        }
    }

框架类

package test;

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

public class frameClass extends JFrame {

    private JButton click;

    public frameClass(){
        setLayout(new FlowLayout());
        click = new JButton("Stop Loop");
        add(click);

        thehandler handler = new thehandler();
        click.addActionListener(handler);
    }

    private class thehandler implements ActionListener{
        public void actionPerformed(ActionEvent e){
            if(e.getSource()==click){
                looper loop = new looper();
                looper.buttonSet = !looper.buttonSet;
            }
        }
    }
}

循环类

package test;

public class looper {
    public static boolean buttonSet;

    public looper(){
        while (buttonSet==false){
            System.out.println("aaa");
        }       
    }
}

请问如何解决这个问题并停止进入无限循环?

最佳答案

Swing 是一个单线程框架,这意味着当循环运行时,事件调度线程被阻塞,无法处理新事件,包括重绘请求...

您需要在它自己的线程上下文中启动您的 Looper 类。这也意味着您的循环标志需要声明为 volatile 或者您应该使用 AtomicBoolean 以便可以跨线程边界检查和修改状态

例如……

public class Looper implements Runnable {

    private AtomicBoolean keepRunning;

    public Looper() {
        keepRunning = new AtomicBoolean(true);
    }

    public void stop() {
        keepRunning.set(false);
    }

    @Override
    public void run() {
        while (keepRunning.get()) {
            System.out.println("aaa");
        }
    }

}

然后你也许可以使用类似...

private class thehandler implements ActionListener {

    private Looper looper;

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == click) {
            if (looper == null) {
                looper = new Looper();
                Thread t = new Thread(looper);
                t.start();
            } else {
                looper.stop();
                looper = null;
            }
        }
    }
}

运行它...

看看Concurrency in SwingConcurrency in Java了解更多详情

另请注意,Swing 不是线程安全的,您永远不应从 EDT 上下文之外创建或修改 UI

关于java - 使用按钮停止和开始循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27662408/

相关文章:

java - Java 应用程序中的 SSH 具有类似 'expect' 的功能

jquery - 使按钮不可见(不隐藏)

java - 如何使菜单栏带在按钮之后消失?

java - 使用 Swing 将 Jpanels 正确添加到 BoxLayout 时遇到问题

Java GUI 布局问题

java - 以编程方式将按钮添加到 fragment

image - 如何将透明图像添加到 MS Access 2010 按钮控件?

java - 嵌入小程序在我的网站上不起作用

java - 如何在文件中保存新路径

java - 当主报表查询有多个结果集并且子报表作为参数输入时无法生成PDF?