Search code examples
javaswingpaintjappletmouse-listeners

Java Applet Excessive Flickering


I'm creating a simple shooting gallery type game. I have create a mouse motion listener and am using to draw an image at the current position of the mouse. This works fine however the image flicker quite a lot when I move the cursor. I have tried several double buffering tutorial however none of these work.

Here is my code

    public class ShootingGallery extends JApplet implements MouseMotionListener {

        //VARIABLES
        int mouseXPos;
        int mouseYPos;
        Image myImage;
        private Image dbImage;
        private Graphics dbg;

        @Override
        public void init() {            
            setSize(800, 600);//SET UP CURSOR IMAGE
            myImage = getImage(getDocumentBase(),"spongebob.gif");
            addMouseMotionListener(this);//ADD ACTION LISTENERS
        }

        @Override
        public void mouseDragged(MouseEvent e) {            
            moveMouse(e); 
        }        

        @Override
        public void mouseMoved(MouseEvent e) {            
            moveMouse(e);
        }        

        public void moveMouse(MouseEvent e){            
              Graphics g = getGraphics();             
              mouseXPos = e.getX() - (myImage.getWidth(null) / 2);
              mouseYPos = e.getY() - (myImage.getHeight(null) / 2);     
              repaint();
        } 

        public void paint(Graphics g)
        {
              super.paint(g);            
              g.drawImage(myImage, mouseXPos, mouseYPos, this);
        }
   }

Any help with this issue is much appreciated


Solution

  • Swing is already supported buffering. Just paint on another container not the top-level one, please see code here:

    public class ShootingGallery extends JApplet implements MouseMotionListener {
    
    // VARIABLES
    int mouseXPos;
    int mouseYPos;
    Image myImage;
    
    @Override
    public void init() {
        setSize(800, 600);// SET UP CURSOR IMAGE
        myImage = getImage(getDocumentBase(), "spongebob.gif");
        addMouseMotionListener(this);// ADD ACTION LISTENERS
        this.add(new PaintContainer());
    
    }
    @Override
    public void mouseDragged(MouseEvent arg0) {
    }
    
    @Override
    public void mouseMoved(MouseEvent e) {
        moveMouse(e);
        repaint();
    }
    
    public void moveMouse(MouseEvent e) {
        mouseXPos = e.getX() - (myImage.getWidth(null) / 2);
        mouseYPos = e.getY() - (myImage.getHeight(null) / 2);
    }
    
    public class PaintContainer extends JPanel {
    
         protected void paintComponent(Graphics g) {
             g.drawImage(myImage, mouseXPos, mouseYPos, this);
         }
    }
    }