Java: while loop freezes program

前端 未结 3 966
鱼传尺愫
鱼传尺愫 2021-01-29 06:50

I\'m making a game and i need to update the JProgressBar every 3 seconds. To do that i use a while loop. The problem is that my program freezes becuse of the while loop (i read

相关标签:
3条回答
  • 2021-01-29 06:54

    You will need to use threads for that. But be careful, and don't try to update the GUI component (JProgressBar) from a thread that does not own the progress bar.

    You should use SwingUtilities.invokeLater to do that.

    0 讨论(0)
  • 2021-01-29 06:59

    You should run your loop in an own Thread:

            new Thread( new Runnable() {
                @Override
                public void run()
                {
                    resourceLoader (null);
                }}).start();
    

    BTW: If you do not use the "String[] args" in the method there is no reason to have it declared in the method.

    0 讨论(0)
  • 2021-01-29 07:15

    I'm not sure what you're trying to do with this program, but there you might want to investigate using a listener instead of rolling your own regular time interval. Also, if your while condition is simply true, it's probably a smell that there is a simpler way to implement the solution - messing with threads is playing with fire.

    https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html

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