visualizing JPanel change within a loop

后端 未结 3 967
感动是毒
感动是毒 2021-01-27 16:55

I am new to Java swing programming. I want to make a frame which will appear red and blue in turn one after another. So, I took 2 child JPanel, 1 for red and other for blue, and

3条回答
  •  孤城傲影
    2021-01-27 17:37

    Basically you don't need to use a while (or any other) loop, Swing only paints once it has finished that loop then repaint the GUI.

    As stated before by @camickr on his answer, you could try a Swing Timer; here's an example that does exactly what you want.

    From your comment on another answer:

    Could you please explain why "repaint" does not work in a loop? And why is the Timer working without a "repaint"?

    Swing is smart enough to know it doesn't needs to repaint in a loop, instead it will repaint once it the loop finishes, if you read the tutorial on Swing Custom Paint on the step 3 it says:

    "Swing is smart enough to take that information and repaint those sections of the screen all in one single paint operation. In other words, Swing will not repaint the component twice in a row, even if that is what the code appears to be doing."

    And Timer will repaint it, because it's not running on the EDT but in it's own Thread

提交回复
热议问题