for循环中Thread.sleep(x)的问题 - Java

Ant*_*que 2 java graphics

我正在制作一个包含圆角矩形的框架.这个矩形经常(重新)用较小的值绘制自己.

计划是,首先矩形的宽度(x)减小,之后矩形的高度(y)减小.

但是现在我只想让宽度减小.但我已经在这里遇到麻烦了.

请注意,我只绘制矩形的边框,所以我不想填充它.

我做了一个for循环如下:

 for (rectWidth = 470; rectWidth >= 0; --rectWidth) {

           try {
                //simply made to represent rectWidth's value, not really relevant
                System.out.println("rectWidth is: " + rectWidth);

                //draw the rectangle with it's new width, ignore the "rectHeight" for now.
                g.drawRoundRect(5, 5, rectWidth, rectHeight, 10, 10);

                //this Thread.sleep is messing up my frame which has an instance of this class added 
                //to it also, my program is uninterruptable when adding this Thread.sleep
                Thread.sleep(500);

            } catch (Exception ex) {
                //rectangle's value will be returned here when interrupted.

          }
         }
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何在我的for循环中添加'sleep'以使绘图不会太快,而不会弄乱我的框架.这个thread.sleep正在弄乱我的框架,我甚至都看不到这个矩形了.

我想实现矩形的平滑(重新)绘画.(是的,我知道,因为这段代码现在不是重新绘制矩形,而是在框架中不断地绘制一个稍小的矩形.)

Jim*_*Jim 5

没有显示矩形的原因是显示在EventDispatchThread上更新,这可能与您的循环所在的相同.也就是说它不能绘制矩形,因为它太忙了睡觉.

解决方案是使用Swing Timer,它将在更新时运行并愉快地将任务发送到EventDispatchThread.