Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Problems repainting... new to Java GUI building...

843807Jan 6 2005 — edited Jan 7 2005
I'm building a simple applet that makes the moon (a jpg) revolve around the earth (another jpg), based off basic sine and cosine x,y coordinates. The program runs fine, however: it repaints the earth and background rectangle everytime the moon moves. Is there some way to make this stuff painted once, and just the moon repainted over and over? Also, is there a way I can just move the moon image, instead of painting it over and over every time? I'm going to be adding to this in the future, but I wanted to get this down first. I had first built this in JavaScript with HTML and CSS for the GUI, so this is a new concept to me.
 import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;

public class Planet extends JApplet implements Runnable {
	
	Thread timer = null;
	Image earth, moon;
	double x, y;
	int spot = 0;
	
	public void init()
   {
   	earth = getImage (getDocumentBase(), "earth1.jpg");
   	moon =  getImage (getDocumentBase(), "moon.jpg");
   	   	
   }
   
   public void PaintComponent (Graphics page)
   {
   	page.setColor (Color.black);
   	page.fillRect (0, 0, 650, 650);	// background black
   	
   	page.drawImage(earth, 245, 245, 160, 160, this);
   }
   public void paint (Graphics page)
   {
   	/*
   	page.setColor (Color.white);
   	for (int i = 0; i < 360; i++)
		{
			x = (290.0 * Math.cos(i * (Math.PI/180.0))) + 325;
			y = (290.0 * Math.sin(i * (Math.PI/180.0))) + 325;
			page.drawOval ((int)x, (int)y, 1, 1);
		}
		*/
		
		page.setColor (Color.black);
   	page.fillRect (0, 0, 650, 650);	// background black
   	
   	page.drawImage(earth, 245, 245, 160, 160, this);
   	
   	x = (280.0 * Math.cos(spot * (Math.PI/180.0))) + 325;
		y = (280.0 * Math.sin(spot * (Math.PI/180.0))) + 325;
   	
   	page.drawImage(moon, (int)x, (int)y, 20, 20, this);
   	
   	spot++;
   	if (spot == 360)
   	{
   		spot = 0;
   	}
   }
   
   public void start() {
  if(timer == null)
    {
      timer = new Thread(this);
      timer.start();
    }
}

public void stop() {
  timer = null;
}

public void run() {
  while (timer != null) {
    try {Thread.sleep(250);} catch (InterruptedException e){}
    repaint();
  }
  timer = null;
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 4 2005
Added on Jan 6 2005
4 comments
95 views