如何在 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 拒绝使用循环,一旦我让它无限。我将如何允许它这样做?

当你使循环"无限"时,你有效地捆绑并冻结了 Swing 事件线程,阻止 Swing 做任何事情。请改用摆动计时器来驱动动画。

例如,

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);  
  }
}

paint 函数应该更新 Paint 并摆脱困境。你真的不应该在那里输入复杂的逻辑,绝对不应该在那里进行无限循环。

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

它永远不会脱离paintComponent循环并更新GUI。GUI 只会在 paintComponent 方法完成后更新。如果你想使循环无限,你需要从事件处理程序中取出代码,并从其他地方调用 repaint((,可能使用计时器来做到这一点。

最新更新