That's because you aren't repainting the background rectangle before you paint the oval. Even so, you really should do your custom painting on a lightweight component such as a JPanel or small JComponent class that overrides paintComponent(), rather then painting directly on the JFrame. Here is your code with a small canvas component for the painting:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Court extends JFrame implements Runnable {
private int x = 10;
private int y = 20;
private int r = 3;
public Court() {
setBounds(0, 0, 200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBackground(Color.BLACK);
// adding the new component here
getContentPane().add(new CanvasComponent());
this.setVisible(true);
start();
}
// Custom component for your paint work.
// JPanel is also a good candidate for this.
class CanvasComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.GREEN);
g.fillOval(x - r, y - r, 2 * r, 2 * r);
}
}
public void run() {
while (true) {
x++;
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
}
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Court();
}
});
}
}//end
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Offline 6,756 posts
since May 2007