Java, applet: How to block the activation of paint() before init() finishes it's work

旧巷老猫 提交于 2019-12-12 04:35:48

问题


I found out that the method paint() gets called some time (it can't happen immediately, can it?) after the activation of init(), not after it finishes. I have a few objects that get created in init() and drawn in the paint() method. But the drawing starts before the objects get initialized. This causes exceptions, that are handled automatically. But it also causes the objects not to get drawn after the the first activation of paint()- they need to be redrawn in order to show up.

I was able to block the paint() method's work with an infinite cycle, placed int the beginning of the method, that doesn't stop until init() finishes it's work (I guess init() and paint() run in separate threads). But an employed Java programmer told me that this isn't an elegant solution- I should try to do something different (the guy didn't tell me what to do, he is not working with applets and I guess, he has never encountered this problem, that's why I'm asking here).

How can I make sure that the paint() method doesn't activate before init() finishes working, and how can I make it in an elegant way (what ever that's supposed to mean in this case...)?

EDIT:

I am using Dr. Java- for some reason, it runs the applet differently on two different computers: a really old laptop (7-years-old) that runs with Win XP and a 2-years-old desktop PC that runs with Win 7. I have made the mistake not to test with a browser...

The problem doesn't occur when testing with Dr. Java on the desktop. And the problem doesn't occur when running the applet on a browser. It only occurs with the editor installed on the laptop. I guess the problem is in the code editor running on the "old tech", not in the code.


回答1:


The short answer is you can't. Init and paint are being called, as you suspected, by two different threads.

The most elegant solutions I think off of is

  1. Check for nulls in the paint method
  2. Use EventQueue.invokeLater in the init method and place the initialisation code within it, calling repaint when you're done



回答2:


public void init() {
   // do my initing...
   inited = true;
   repaint();
}

public void paint(Graphics g) {
   if (!inited) {
      return;
   }

   // do my painting...
}


来源:https://stackoverflow.com/questions/13710524/java-applet-how-to-block-the-activation-of-paint-before-init-finishes-its

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!