Stoppen Sie das flackern in einfache Java-Animationen

Habe ich ein einfaches applet, das animiert ein Rechteck entlang der x-Achse der Leinwand. Das problem ist, dass es flackert. Ich habe versucht, Google diesem problem, aber ich wollte nicht kommen mit etwas sinnvolles oder etwas, das habe ich verstanden.

Ich bin relativ neu in Java.

Dank!

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*; 

public class simpleAnimation extends JApplet implements ActionListener { 
    Timer tm = new Timer(10, this); 
    int x = 0, velX = 2;

    public void actionPerformed(ActionEvent event) { 
        if (x < 0 || x > 550){ 
            velX = -velX; 
        }

        x = x + velX; 
        repaint(); 
    }

    public void paint ( Graphics g ) { 
    super.paint(g); 
    g.setColor(Color.RED); 
    g.fillRect(x, 30, 50, 30); 
    tm.start(); 
    } 
}

**********AKTUALISIERT CODE OHNE FLIMMERN**********

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class simpleAnimation extends JApplet implements ActionListener  
{ 

     Graphics bufferGraphics; 

     Image offscreen; 

     Dimension dim; 

     int x = 3, velX = 2;

     Timer tm = new Timer(10, this);

     public void init()  
     { 

          dim = getSize(); 

          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.fillRect(x,50,50,20); 

          g.drawImage(offscreen,0,0,this); 

          tm.start();   

     }

     public void update(Graphics g) 
     { 

          paint(g); 

     } 

    public void actionPerformed(ActionEvent evt) 
    {   

        if ( x < 0 || x > 550){

            velX = -velX;

        }

        x = x + velX;   

        repaint();

    }

 }

Habe ich dieses applet als Vorlage.

InformationsquelleAutor this_guy | 2013-11-04
Schreibe einen Kommentar