I realize most of the Java code to overwritten paint or paintComponent, most of them doesn't restore the old state of graphics object, after they had change the state of graphics object. For example, setStroke, setRenderingHint...
I was wondering whether it is a good practice that we restore back the old state of graphics object, before returning from the method. For example
public void paintComponent(Graphics g) {
super.paintComponet(g);
Stroke oldStroke = g.getStroke();
g.setStroke(newStroke);
// Do drawing operation.
g.setStroke(oldStroke);
}
Is this a good practice? Or it is over done?
You should not alter the Graphics object passed in at all, rather perform all your graphics operations on a copy of it which you then dispose. There'll be no need to reset the state at all then.
public void paintComponent(Graphics g1) {
super.paintComponent(g1);
final Graphics2D g = (Graphics2D)g1.create();
try {
// ...Whole lotta drawing code...
} finally {
g.dispose();
}
}
Yes, this is a very good practice to follow. You don't pay much in performance (relative to the actual painting operation), and you save yourself a mess of grief if you're making unusual changes to the graphics context. Don't overdo it though -- you probably don't need to worry about color settings, for example.
The alternative is to assume nothing about the graphics context, and set all the necessary properties before every painting, in case they're set to something wonky. Try to avoid freely creating and disposing Graphics objects for every operation.
Specific properties you should always restore if modified: (because they can do Bad Things and have Unexpected Consequences):
Properties to not worry about:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With