如何在JPanel中引起无限循环

时间:2015-04-07 22:17:47

标签: java swing jpanel

class DrawPane extends JPanel
{
  //size is the size of the square, x and y are position coords
  double size = 1, x = 0, y = 0;
  double start = (-1) * size;
  public void paintComponent(Graphics shape)
  {
    for(x = start; x <= scWidth; x += size)
    {
      shape.drawRect((int)x, (int)y , (int)size, (int)size);

      //When a row is finished drawing, add another
      if(x >= scWidth)
      {
        x = start; y += size;
      }

      //Redraws the entire grid; makes the for loop infnite
      else if(y >= scHeight)
      {
        x = start; y = start;
      }
    }
  }
}

我很困惑为什么JPanel在无限循环后拒绝使用循环。我将如何允许它这样做?

3 个答案:

答案 0 :(得分:3)

当你使循环“无限”时,你有效地绑定并冻结Swing事件线程,阻止Swing做任何事情。而是使用Swing Timer来驱动动画。

如,

class DrawPane extends JPanel {
  //size is the size of the square, x and y are position coords
  double size = 1, x = 0, y = 0;
  double start = (-1) * size;

  public DrawPane() {
    int timerDelay = 200;
    new Timer(timerDelay, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            x += size;
            if (x >= scWidth) {
                x = start;
                y += size;
            }
            if (y >= scHeight) {
                x = start;
                y = start;
            }
            repaint();
        }
    }).start();
  }

  public void paintComponent(Graphics g)   {
    super.paintComponent(g); // Don't forget to call this!
    g.drawRect((int)x, (int)y , (int)size, (int)size);  
  }
}

答案 1 :(得分:0)

paint函数应该更新Paint并且不用了。你真的不应该投入复杂的逻辑,绝对不是无限循环。

做你所拥有的(除了摆脱使你的循环无限的重置东西)并将repaint()置于程序中其他地方的无限循环(最好带有一些计时器逻辑)。

答案 2 :(得分:0)

它永远不会脱离paintComponent循环并更新GUI。只有paintComponent方法完成后,GUI才会更新。如果你想让循环无限,你需要从你的事件处理程序中取出代码并从其他地方调用repaint(),可能使用定时器来执行此操作。