proplem in updating JLabel in for loop

强颜欢笑 提交于 2019-12-02 19:56:11

问题


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 !");
    }
}

回答1:


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

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

See more at How to use Swing Timers



来源:https://stackoverflow.com/questions/21795183/proplem-in-updating-jlabel-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!