Java – overwrite paint or paintcomponent when you need to restore the original state of the drawing
•
Java
I realized that most of the Java code covered paint or paintcomponent, and most of them did not restore the old state of the graphic object after they changed the state of the graphic object For example, setstroke, setrenderinghint
I wonder if it is a good practice to restore the old state of graphical objects 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 habit? Or is it finished?
Solution
You should not change the passed graphics object, but perform all graphics operations on the copy you process There is no need to reset the status
public void paintComponent(Graphics g1) { super.paintComponent(g1); final Graphics2D g = (Graphics2D)g1.create(); try { // ...Whole lotta drawing code... } finally { g.dispose(); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码