简体   繁体   English

Java:同时运行多个while循环

[英]Java: Run multiple while loops at the same time

I'm trying to make several JRadioButtons blink at the same time with this blink method: 我正在尝试使用此眨眼方法同时使几个JRadioButtons眨眼:

private void blink(JRadioButton button, boolean blinking)
{
    if(blinking)
    {
        while(true)
        {   
            try 
            {
                button.setSelected(true);
                Thread.sleep(500);
                button.setSelected(false);
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    else
    {
        button.setSelected(false);
    }
}

I know it has something to do with threads but I'm not that familiar with them. 我知道它与线程有关,但我对线程并不熟悉。

I'm trying to make several JRadioButtons blink at the same time with this blink method 我正在尝试使用此眨眼方法同时使几个JRadioButtons眨眼

IMHO you don't need multiple while loops. 恕我直言,您不需要多个while循环。

Just add all buttons you want to blink to an ArrayList , then in the same while loop, loop over that list and blink the buttons. 只需将要闪烁的所有按钮添加到ArrayList ,然后在同一while循环中,遍历该列表并使按钮闪烁。 So, instead of 所以,代替

button.setSelected(true);
Thread.sleep(500);
button.setSelected(false);
Thread.sleep(500);

You can use 您可以使用

for(int i=0; i<yourList.size(); i++) {
    yourList.get(i).setSelected(true);
}
Thread.sleep(500);
for(int i=0; i<yourList.size(); i++) {
    yourList.get(i).setSelected(false);
}
Thread.sleep(500);

But this is a bad practice. 但这是一个不好的做法。 Use the Timer class and schedule a thread to execute every 500 ms instead: 使用Timer类并安排线程每500毫秒执行一次:

Timer t = new Timer(500, new ActionListener() {
    boolean selected = false; 

    @Override
    public void actionPerformed(ActionEvent e) {
        selected = !selected;
        for(int i=0; i<yourList.size(); i++) {
            yourList.get(i).setSelected(selected);
        }
    }
});
t.start();

You can't animate the GUI by using Thread.sleep . 您无法使用Thread.sleep为GUI设置动画。 In fact, you must never call Thread.sleep on the Event Dispatch Thread because that very thread is in charge of repainting the GUI, which it will clearly not be able to do while sleeping. 实际上,您绝不能在事件调度线程上调用Thread.sleep ,因为该线程负责重绘GUI,而显然它在睡眠时将无法执行此操作。

What you must use is the Swing Timer class and schedule it to repeat at the desired interval. 您必须使用Swing Timer类,并安排它以所需的时间间隔重复执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM