Java 2D Graphics Finally, the initial release of
Java 2D Graphics calculateFrameRate(); } } You may be wondering what render() does. Why not just call repaint()? The reason has to do with how repaint() works. The problem is that repaint() doesn’t do the drawing right away. That is, it doesn’t call the component’s paint() method directly. Instead, it tells AWT to redraw the component the next time it gets a chance. In a tight animation loop like this one, AWT doesn’t ever get a chance to redraw the window.[1] Because of this, the render() method actually does the drawing directly. The render() method implements one other nice feature: double buffering. It draws the component into an offscreen image and then renders the image on the screen. [1] Be careful if you decide to port this class to Swing. Threading in Swing is a bit more subtle; for more details, see Java Swing , by Robert Eckstein, Marc Loy, and Dave Wood (O’Reilly). protected void render() { Graphics g = getGraphics(); if (g != null) { Dimension d = getSize(); if (checkImage(d)) { Graphics imageGraphics = mImage.getGraphics(); // Clear the image background. imageGraphics.setColor(getBackground()); imageGraphics.fillRect(0, 0, d.width, d.height); imageGraphics.setColor(getForeground()); // Draw this component offscreen. paint(imageGraphics); // Now put the offscreen image on the screen. g.drawImage(mImage, 0, 0, null); // Clean up. imageGraphics.dispose(); } g.dispose(); } } There are two Graphics objects involved. The first, g, is the drawing surface of the onscreen component. The second, imageGraphics, is the drawing surface of the offscreen image. All the painting is performed on imageGraphics. Then the offscreen image is rendered to g to put it on the screen. AnimationComponent also calculates the frame rate of the animation. The basic algorithm for calculating the frame rate is to find the amount of time between two adjacent frames and take the reciprocal. Because the times are measured in milliseconds, the result is multiplied by 1000 to get frames per second: This result, however, fluctuates wildly depending on the current state of the system. It is also subject to the resolution of the clock.[2] For more stable results, AnimationComponent calculates an average frame rate. It keeps an array of frame times in the mPreviousTimes array and calculates the frame rate based on the oldest entry in that array. Until this array is filled, however, AnimationComponent uses the previous method. Here’s the code for calculateFrameRate(): [2] On my Windows NT system, for example, I only get readings in multiples of ten milliseconds. protected void calculateFrameRate() { page 255
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services