My code:
import java.awt.*;
import javax.swing.*;
public class BouncingBall extends JFrame {
JFrame frame;
Ball mainpanel;
protected Color ballColor = Color.blue;
protected int radius = 20;
protected int x, y, dx, dy;
protected Image image;
protected Graphics offscreen;
private Thread ballThread;
public static void main(String[] args) {
BouncingBall bb = new BouncingBall();
bb.go();
}
public void go(){
x = 250;
y = 225;
dx = 2;
dy = 2;
frame = new JFrame("Bouncing Ball");
mainpanel = new Ball();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 450);
frame.getContentPane().add(mainpanel);
frame.setVisible(true);
mainpanel.start();
}
public class Ball extends JPanel implements Runnable{
public void start(){
ballThread = new Thread(this);
ballThread.start();
}
public void stop(){
ballThread = null;
}
public void run(){
while(Thread.currentThread() == ballThread){
try{
Thread.currentThread().sleep(10);
}catch (InterruptedException e){}
repaint();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Dimension d = getSize();
if(image == null){
image = createImage(d.width, d.height);
offscreen = image.getGraphics();
}
//offscreen.setColor(Color.white);
//offscreen.fillRect(0, 0, d.width, d.height);
offscreen.setColor(ballColor);
offscreen.fillOval(x, y, 2*radius, 2*radius);
g.drawImage(image, 0, 0, this);
if (x <= 0 || x >= d.width - 2*radius)
dx = -dx;
if (y <= 0 || y >= d.height - 2*radius)
dy = -dy;
x+=dx;
y+=dy;
}
}
}
Basically, in the paintComponent() method of the Ball class, the
super.paintComponent(g)that is supposed to clear the screen before drawing the circle isn't clearing the screen. I've searched fairly extensively for solutions to this, but I keep coming across threads where the ANSWER is to use
super.paintComponent(g). However, in this case, it is not clearing and the ball streaks across the screen leaving a trail wherever it goes. As you can see, I used a bandaid solution of filling a white rectangle the size of the frame, but that is not acceptable.
Can anyone explain why the JPanel's super.paintComponent(g) isn't clearing the screen as it should (as it has been said in many threads)? Thanks in advance.

New Topic/Question
Reply



MultiQuote





|