更新JLabel for for循环的问题 [英] proplem in updating JLabel in for loop

查看:175
本文介绍了更新JLabel for for循环的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序的想法是从之前在其他JFrame中保存的列表中选择一个名称。我想在标签上一个接一个地打印所有名字,它们之间有很小的延迟,然后在其中一个停止。问题是 lbl.setText(String); 如果有多个 setText ,则不起作用码。

The idea of my program is to select one name from a list that saved before in other JFrame. I'd like to print in the label all names one after the other with small delay between them, and after that stop at one of them. The problem is that lbl.setText("String"); doesn't work if there is more than one setText code.

这是我的代码的一部分:

Here is the part of my code :

public void actionPerformed(ActionEvent e)
{
    if (RandomNames.size != 0) 
    {
        for (int i = 0; i < 30; i++)
        {
            int rand = (int)(Math.random() * RandomNames.size);   
            stars.setText(RandomNames.list.get(rand));

            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException err)
            {
                err.printStackTrace();
            }
        }

        int rand2 = (int)(Math.random() * RandomNames.size);
        stars.setText(RandomNames.list.get(rand2));
        RandomNames.list.remove(rand2);
        RandomNames.size = RandomNames.list.size();

    }

    if (RandomNames.list.size() == 0)
    {
        last.setText("\u062A\u0645 \u0638\u0647\u0648\u0631 \u062C\u0645\u064A\u0639 \u0627\u0644\u0623\u0633\u0645\u0627\u0621 \u0627\u0644\u062A\u064A \u0641\u064A \u0627\u0644\u0642\u0627\u0626\u0645\u0629 !");
    }
}


推荐答案

Don不要使用循环或 Thread.sleep 。只需使用 javax.swing.Timer 。以下将导致每1000毫秒发生30次迭代。您可以根据您希望每隔几毫秒发生的事情调整 actionPerformed 中的代码。

Don't use a loop or Thread.sleep. Just use a javax.swing.Timer. The following will cause 30 iterations occurring every 1000 milliseconds. You can adjust the code in the actionPerformed accordingly to what you wish to happen every so many milliseconds.

int count = 0;
...
Timer timer = new Timer(1000, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        if (count == 30) {
            ((Timer)e.getSource()).stop();
        } else {
            int rand = (int) (Math.random()* RandomNames.size);   
            stars.setText(RandomNames.list.get(rand));
            count++;
        }
    }
});
timer.start();

如果你想要,你可以设置计时器在构造函数中, start()它在另一个按钮的监听器的 actionPerformed 中。

If you want you can just set up the Timer in the constructor, and start() it in the actionPerformed of another button's listener.

更多信息,请访问如何使用Swing计时器

这篇关于更新JLabel for for循环的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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