Search code examples
javaanimationobserver-patternrepaint

Java -- For an animation, how should a logic class notify a loosely coupled view to repaint


For an application that repaints frequently, how should the 'model' notify the 'views' that they need to repeatedly repaint one of their components. This:


class AppLogic extends Observable {
  void runAnimation() {
    while (isAnimationRunning) {
      modifyDataStructures();
      setChanged();
      notifyObservers();
      Thread.sleep(25);
    }
  }
}

class View extends JComponent implements Observer { void update(Observable o) { o.getData(); innerPanel.repaint(); } }

seems like a terrible way to go about animating a panel, especially if the animation is being repainted most of the time that the program is running. Any suggestions? Thanks.

*Ignore the obvious errors in threading and such


Solution

  • Assuming that you are building a kind of "Dashboard" application that updates the information periodically, do what this answer says. If you want something more advanced (like animations for a game) you need more work. Check this article for some interesting tidbits about game programming and animation in Java.