visualizing JPanel change within a loop

后端 未结 3 966
感动是毒
感动是毒 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:34

    Don't use a loop. Swing will only repaint the frame once the entire loop has finished executing.

    Instead you need to use a Swing Timer. When the Timer fires you invoke your logic. Read the section from the Swing tutorial on How to Use Swing Timers.

    Here is a simple example of a Timer that simply displays the time every second: Update a Label with a Swing Timer

    Also, don't remove/add panels. Instead you can use a Card Layout and sway the visible panel. Again read the tutorial on How to Use CardLayout.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-27 17:42

    I would suggest to take in one step at a time.
    First make it run without changing panels / colors.
    Now it doesn't because this

    public final void Test2() {
    

    is a method (which is never used) and not a constructor. Change to a constructor declaration like :

    public  Test2() {
    

    to make the program do something. Then you can go to the next step.

    Also use Java naming conventions (like blue instead of Blue).

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