B
Bob
I am tring to make a simple animated ball the code at the under, and to stop
flickering I tried to use some code I found for double buffering at bottom
but I cannot get it to work can anyone help me?
import javax.swing.JApplet;
import java.awt.*;
public class Ball2 extends JApplet {
private int x = 0;
private int y = 0;
private int dx = 1;
private int dy = 2;
private int diameter = 50;
private int width = 0;
private int height = 0;
public void init() {
width = getSize().width;
height = getSize().height;
}
public void paint(Graphics g) {
while (true) {
try {Thread.sleep(75);}
catch(Exception e){}
x += dx;
if (x < dx) dx = dx+10;
if (x > width-diameter) dx = -dx-10;
y += dy;
if (y < dy) dy = dy+10;
if (y > height-diameter) dy = -dy-10;
g.setColor(this.getBackground());
g.fillRect(0,0,width,height);
g.setColor(Color.red);
g.fillOval(x,y,diameter,diameter);
}
}
}
Double Buffering
Image offImage;
Graphics offScreen;
public void update(Graphics g)
{
Dimension dim =getSize();
if(offScreen==null)
{
offImage=createImage(dim.width,dim.height);
offScreen=offImage.getGraphics();
}
offScreen.setColor(getBackground());
offScreen.fillRect(0,0,dim.width,dim.height);
offScreen.setColor(getForeground());
offScreen.drawImage(offImage,0,0,this);
g.drawImage(offImage,0,0,null);
}
flickering I tried to use some code I found for double buffering at bottom
but I cannot get it to work can anyone help me?
import javax.swing.JApplet;
import java.awt.*;
public class Ball2 extends JApplet {
private int x = 0;
private int y = 0;
private int dx = 1;
private int dy = 2;
private int diameter = 50;
private int width = 0;
private int height = 0;
public void init() {
width = getSize().width;
height = getSize().height;
}
public void paint(Graphics g) {
while (true) {
try {Thread.sleep(75);}
catch(Exception e){}
x += dx;
if (x < dx) dx = dx+10;
if (x > width-diameter) dx = -dx-10;
y += dy;
if (y < dy) dy = dy+10;
if (y > height-diameter) dy = -dy-10;
g.setColor(this.getBackground());
g.fillRect(0,0,width,height);
g.setColor(Color.red);
g.fillOval(x,y,diameter,diameter);
}
}
}
Double Buffering
Image offImage;
Graphics offScreen;
public void update(Graphics g)
{
Dimension dim =getSize();
if(offScreen==null)
{
offImage=createImage(dim.width,dim.height);
offScreen=offImage.getGraphics();
}
offScreen.setColor(getBackground());
offScreen.fillRect(0,0,dim.width,dim.height);
offScreen.setColor(getForeground());
offScreen.drawImage(offImage,0,0,this);
g.drawImage(offImage,0,0,null);
}