What is the best way to work with AWT graphics contexts?

Some users of our Swing app report unusual artifacts that appear on the display. This varies from components that do not properly redraw to the second or two parts, to the point that all parts of the application will be repainted like tiled wallpapers over areas of the window.

The application was developed by developers of all levels between experienced Java guys and young guys from the university for five years or so, and, as expected, some of the AWT code is a complete mess, Now I was faced with the task of trying to fix the same bad. as much as I can, over the next few months or so.

This is easy to handle. Only deal with components in the event dispatch stream, IO asynchronously, something like that, and I hope that the message will be sent to the rest of the command.

What I would like to know is the best way to work with Graphics contexts, especially in the context of paintComponent (). I see a lot ...

public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D gfx = (Graphics2D)g; // ...Whole lotta drawing code... } 

Is it better 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 will be reused in other colors, then I do not need to restore it to a good state, cancel AffineTransforms, etc.

+4
source share
2 answers

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

The correct way to handle it is somewhat more detailed:

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

IIRC, in a Sun implementation, it doesn’t matter if you don’t destroy subgraph objects. (Do not quote me on this.)

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

+5
source

I heard that this was fixed in jdk-1.6.12, but have not tried.

-1
source

All Articles