Java JToggleButton在While循环中冻结 [英] Java JToggleButton freezes in While loop

查看:174
本文介绍了Java JToggleButton在While循环中冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void playMet() {

    int tempo = Integer.parseInt(met_speed.getText());
    tempo = tempo/60;
    int delay = tempo*1000; 

    if(Play.isSelected()) {
        try {
            FileInputStream in = new FileInputStream(new File("Click1.wav"));

            AudioStream as = new AudioStream(in);
            AudioPlayer.player.start(as);

            Thread.sleep(tempo*1000);
            playMet();

        } 
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

    } 
    else
        System.out.println("not playing");
}

这是我的代码的一部分,基本上当按下按钮时它会播放每分钟点击X次。

Here's a section of my code, basically when a button is pressed it plays a click X times per minute.

我用这样的while循环尝试了代码:

I've tried the code with a while loop like this:

while(Play.isSelected()) {
.........
.........
}

这也不起作用。在这两种情况下,程序都应该运行,但冻结,我必须从任务管理器关闭它。

and that didn't work either. In both cases the program runs like it should, but freezes and I have to close it down from the task manager.

如何在按下按钮时调用某个函数,如果取消选择它可以停止它?

How can I call a function when the button is pressed and be able to stop it if I deselect it?

PS刚看到下面的两个帖子。必须去上班,稍后会检查它们,看看它们是否有效。感谢您的帮助。

P.S. Just saw the two posts below. Have to go to work, will check up on them later and see if they work. Thank you for the help.

推荐答案

递归调用阻止事件派遣线程。你必须创建一个新的线程来阻止EDT。

The recursive calls are blocking the Event Dispatch Thread. You have to create a new Thread to not block the EDT.

public void playMet()
{
    Thread t = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            while(Play.isSelected()){
                //Your code
            }
        }
    };
    t.start();
}

这篇关于Java JToggleButton在While循环中冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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