views:

91

answers:

2

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.?

A: 

I heard that this has been fixed in jdk-1.6.12, but didn't try it.

Dev er dev
+4  A: 

According to Filthy Rich Clients, you should not alter the Graphics object passed to you (which sucks as an API, IMO).

The correct way to handle it is slightly more verbose:

public void paintComponent(Graphics g1) {
    super.paintComponent(g1);
    final Graphics2D g = (Graphics2D)g1.create();
    try {
         // ...Whole lotta drawing code...
    } finally {
         g.dispose();
    }
}

IIRC, in the Sun implementation it doesn't matter if you don't dispose of "sub-Graphics" objects. (Don't quote me on that.)

You might want to delegate that comment bit to another object.

Tom Hawtin - tackline