简体   繁体   English

在for循环中更新JLabel的问题

[英]proplem in updating JLabel in for loop

The idea of my program is to select one name from a list that saved before in other JFrame. 我程序的想法是从以前保存在其他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"); 问题是lbl.setText("String"); doesn't work if there is more than one setText code. 如果有多个setText代码,则无法使用。

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't use a loop or Thread.sleep . 不要使用循环或Thread.sleep Just use a javax.swing.Timer . 只需使用javax.swing.Timer The following will cause 30 iterations occurring every 1000 milliseconds. 以下将导致每1000毫秒发生30 次迭代 You can adjust the code in the actionPerformed accordingly to what you wish to happen every so many milliseconds. 您可以根据希望每隔几毫秒发生一次的操作来调整actionPerformed的代码。

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();

If you want you can just set up the Timer in the constructor, and start() it in the actionPerformed of another button's listener. 如果需要,您可以只在构造函数中设置Timer ,然后在另一个按钮的侦听器的actionPerformedstart()它。

See more at How to use Swing Timers 如何使用Swing计时器中查看更多信息

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

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