public class H2O extends JComponent implements Runnable {
private int dx = 0, dy = 0;
public H2O() {
this.setPreferredSize(new Dimension(100, 100));
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(60 + dx, 50 + dy, 10, 10);
g.fillOval(50 + dx, 60 + dy, 10, 10);
g.setColor(Color.RED);
g.fillOval(45 + dx, 45 + dy, 20, 20);
}
@Override
public void run() {
while (true) {
dx = (int) (Math.random() * 20 - 10);
dy = (int) (Math.random() * 20 - 10);
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
}