Search code examples
javaswingjlabelgraphics2dpaintcomponent

How to wait for setIcon() method to execute before resuming the code?


I have a code that goes like this:

jLabel.setIcon(map);
Graphics2D g = (Graphics2D) jLabel.getGraphics();
g.drawPolygon(xpoints,ypoints,vpolygonpointsarray.length);

But what happens is that the polygon is drawn first before the labels icon is updated. I suspect setting an icon creates a new thread. I would like to wait until the icon is set before the rest of the code is executed. How would I do that?


Solution

  • You should do your custom painting code in an overridden paint method (paint(), paintComponents() etc.). Check here: http://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html