proplem in updating JLabel in for loop

前端 未结 1 1996
陌清茗
陌清茗 2021-01-27 12:57

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 betwee

1条回答
  •  一个人的身影
    2021-01-27 13:33

    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

    0 讨论(0)
提交回复
热议问题