proplem in updating JLabel in for loop

自作多情 提交于 2019-12-02 07:47:53

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

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