hi,
what is the correct way of active rendering in swing ? such an animation loop doesnt cause the component (a custom JPanel) to be repainted immediately ?
while(running) {
// game and render stuff here
//..
component.repaint(); // this wont make the component to be painted immediately, but later
}
repaint(0) wont help either since loop will continue running and repaint(0) requests will coalesce
if component.repaint() is replaced with
component.paintImmediately(component.getBounds());
this also fails since animation loop doesnt run in AWT-Thread’s context. If we run these in AWT-Thread then we block the AWT-Thread and cause AWT and Swing events not to be dispatched. i looked for a method to dispatch all waiting AWT events and return but couldnt find.
well, infact running this loop in another thread will succesfully and actively draw the component but that way we lack swing layout features. to be precise, i use the component at bottom of a JLayeredPane and there are other components on top of that. since we call component.paintImmediately() in another thread swing gets out of sync and those other components disappear or flicker
the only solution i can think of is to use:
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
component.paintImmediately(component.getBounds());
}
});
instead of component.repaint(). but this is error-prone and one can easily fall into deadlock trap (as i did ::)), and worse enough it is too expensive because of context switching
so what is the solution ?
thx
r a f t