Pre-optimization code:
Packagecom;Importjavax.swing.*;Importjava.awt.*;/*** Using Eclipse, right-click Run As,java applet running * Pre-Optimization effect: screen jitter and white light effects *@authorHu Jinshui **/ Public classNobuffermovingcircleextendsJAppletImplementsRunnable {Image screenimage=NULL; Thread thread; intx = 5; intmove = 1; Public voidinit () {screenimage= CreateImage (230,160); } Public voidstart () {if(Thread = =NULL) {Thread=NewThread ( This); Thread.Start (); }} @Override Public voidrun () {Try{ while(true) {x+=move; if((x > 105) | | (X < 5) {Move*=-1; } repaint (); Thread.Sleep (10); } }Catch(Exception e) {}} Public voiddrawcircle (Graphics GC) {graphics2d g=(GRAPHICS2D) GC; G.setcolor (Color.green); G.fillrect (0,0,200,100); G.setcolor (color.red); G.filloval (x,5,90,90); } Public voidPaint (Graphics g) {G.setcolor (color.white); G.fillrect (0,0,200,100); Drawcircle (g); }}
Optimized code:
Packagecom;ImportJava.awt.Color;ImportJava.awt.Graphics;/*** No screen jitter or white light effect when running with Java applet * Optimized@authorHu Jinshui **/ Public classBuffermovingcircleextendsnobuffermovingcircle{Graphics DoubleBuffer=NULL;//buffers Public voidinit () {Super. Init (); DoubleBuffer=Screenimage.getgraphics (); } Public voidPaint (Graphics g) {//use buffer to optimize the original paint () methodDoublebuffer.setcolor (Color.White);//draw in memory firstDoublebuffer.fillrect (0, 0, 200, 100); Drawcircle (DoubleBuffer); G.drawimage (Screenimage,0, 0, This);//display the buffer once. }}
Buffering optimization of Java Program performance optimization