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'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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top