donderdag 31 maart 2011

Double Buffering in applet source code/listing

Below is a applet that has double buffering. It draws a rectangle beneath your mouse pointer. i found the original source on the internet and removed the comments. This example is one of the things you need to program games.





 


import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class DoubleBuffering extends Applet implements MouseMotionListener
{
     Graphics bufferGraphics;
     Image offscreen;
     Dimension dim;
     int curX, curY;

     public void init()
     {
          dim = getSize();
          addMouseMotionListener(this);
          setBackground(Color.black);
          offscreen = createImage(dim.width,dim.height);
          bufferGraphics = offscreen.getGraphics();
     }

      public void paint(Graphics g)
     {
          bufferGraphics.clearRect(0,0,dim.width,dim.width);
          bufferGraphics.setColor(Color.red);
          bufferGraphics.drawString("Move the mouse in this applet",10,10);
          bufferGraphics.fillRect(curX,curY,20,20);
          g.drawImage(offscreen,0,0,this);
     }

     public void update(Graphics g)
     {
          paint(g);
     }


     public void mouseMoved(MouseEvent evt)
     {
          curX = evt.getX();
          curY = evt.getY();
          repaint();
     }


     // The necessary methods.
     public void mouseDragged(MouseEvent evt)
     {
     }

 }




If you copy and paste this in your java editor be sure to have the name of the project the same as the class name. In this case DoubleBuffering. Also note that java is case sensitive and a applet will not be loaded if the characters of the filename are not completly the same.

Geen opmerkingen:

Een reactie posten