/*********************************************** * Applet that your homework will be based off of **********************************************/ import java.awt.*; import java.util.StringTokenizer; public class Blink extends java.applet.Applet implements Runnable { // the animation thread Thread blinkThread; // the text to blink String blinkingtext; // the text font Font font; // the speed of the blinking in miliseconds int speed; // set up the applet to run public void init() { font = new Font("TimesRoman", Font.PLAIN, 24); speed = 400; blinkingtext = "This is a simple blinking text applet for demonstration in SE 450"; } public void paint(Graphics g) { // the variables for the location of the string // the y gets set to the height of the font int x = 0, y = font.getSize(), space; // randomly determine what the color is going to be int red = (int)(Math.random() * 50); int green = (int)(Math.random() * 50); int blue = (int)(Math.random() * 256); // the size of the applet region Dimension d = getSize(); g.setColor(Color.black); g.setFont(font); // the font metrics object is used to get information // about the current font FontMetrics fm = g.getFontMetrics(); // determine how wide a blank space is in this font. space = fm.stringWidth(" "); // the StringTokenizer will break up the text for the applet // up into individual words. // the "for" loop processes each individual word for (StringTokenizer t = new StringTokenizer(blinkingtext); t.hasMoreTokens() ; ) { // the current word that you are working with String word = t.nextToken(); // add the length of a space to the length of the word int w = fm.stringWidth(word) + space; // this checks to see if the word + the space will fit on the // current line. // if not, it moves the word to the next line. // if it will fit then it just adds it on. if (x + w > d.width) { x = 0; y += font.getSize(); } // this is how you get the words to dissapear. // if the random is less than .5 the word gets // drawn in the color. // if it's not, then the word gets drawn in the // background color, and seems to disappear if (Math.random() < 0.5) { g.setColor(new Color((red + y * 30) % 256, (green + x / 3) % 256, blue)); } else { g.setColor(getBackground()); } // actually draw the word on the screen g.drawString(word, x, y); // move the "cursor" over in preparation for the next word. x += w; } } // start the animation thread up public void start() { blinkThread = new Thread(this); blinkThread.start(); } // stop the animation thread public void stop() { blinkThread = null; } // periodically make the applet repaing. // this is what causes the blinking effect. public void run() { while (Thread.currentThread() == blinkThread) { repaint(); try { Thread.currentThread().sleep(speed); } catch (InterruptedException e){} } } }