Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.
The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.
Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.
What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g;
// ...Whole lotta drawing code...
}
Is it better practice to do this?
public void paintComponent( Graphics g ) {
super.paintComponent( g );
Graphics2D gfx = (Graphics2D)g.create();
// ...Whole lotta drawing code...
gfx.dispose();
}
If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?