applet

axn 0 Tallied Votes 155 Views Share

need this to change to random colors every .8 secs. compiles ok, but not getting wanted results. cant figure out where i am wrong?
i get the applet viewer window with a black square but no color change.

Here is the .html file

<applet code = ColorChange .class width = 300 height = 300>
</applet>

import java.applet.*;
import java.awt.*;

public class ColorChange extends Applet  {

	Color c;
    boolean done;
    public void start() {
    	done = false;
        Thread t = new Thread();
        // start thread countdown
        t.start();
    }
    public void stop() {
        done = true;
    }
    public void paint(Graphics g) {
		super.paint(g);
        g.fillRect(100,100,130,130);
    }
    public void run(){
        while(! done) {
        	c = new Color((int)(255*Math.random()),
                          (int)(255*Math.random()),
                          (int)(255*Math.random()));
            this.setForeground(c);
            try {
            	Thread.sleep(800); // sleep for .8 sec
            }
            catch(InterruptedException e) { } // ignore interuptions
        }
    }
}
cbarton.a 0 Newbie Poster

Axn,
I wouldn't sleep the Thread, I would use a timer to instance the events to fire a repaint().

Here is the working code with comments to help you learn what is going on:

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class DaniProject extends Applet {
	Color c; // Start off black
	
    // Applets require the init() method like normal applications require the main() method.
	 public void init(){
		Timer timer = new Timer(800, new TimerHandler()); // Here we will instantiate a timer with
								// 800 MS delay (.8s) and register a new actionlistener for the
								// tick events.
	    timer.start(); // Start the timer and fire an event.
	 }
    
	 // On the timer events we will create a new color and repaint the window.
    private class TimerHandler implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		generateColor();
    		repaint();
    	}
    }
    
    // Set the color the Graphics class will use and fill up your rectangle.
    public void paint(Graphics g) {
		super.paint(g);
		g.setColor(c);
        g.fillRect(100,100,130,130);
    }
    
    public void generateColor(){
    		c = new Color((int)(255*Math.random()),
                (int)(255*Math.random()),
                (int)(255*Math.random()));
    }    
}

Welcome, please private msg me if any questions,
cbarton.a

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.