开发者

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

开发者 https://www.devze.com 2023-02-16 15:06 出处:网络
For an application that repaints frequently, how should the \'model\' notify the \'views\' that they need to repeatedly repaint one of their components. This:

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();
      开发者_C百科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


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.


Rather than "running" the business logic, you could use a Swing Timer in the View component and just ask the business model to paint itself, e.g passing the current time as a parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消