advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

PetQuotes


//Author:   James Punteney
//Date:     3/24/98
//Purpose:  Scrolls through a list Pet quotes provided


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class PetQuotes extends java.applet.Applet
{
	//Formatting variables
   String fontType;        //Font characteristics
   Color font_color, backGroundColor;    //Applet Colors
   Font f;
   int font_size;

   //Quote Variables
	String quote = "Like a graceful vase, a cat, even when motionless, seems to flow.", author = "George F. Will";
	String line[] = new String[30];  //Holds individual lines of the quotes for display
	int l = 0;  //Keeps track of the number of lines in a quote.

	//Variables that change depending on quote type (pets, dogs, cats)
	//PetQuotes
	String bakQuote = "Whoever said you can’t buy happiness forgot about little puppies.";  // Insert Quote in case it can't open one
	String bakAuthor = "Gene Hill"; //Insert Author for backup quote
	String strFile = "petQuotes.txt";  //Insert file name to read quotes for
	String urlString = "http://www.simplypets.com/redirects/petQuotes.html"; //Where the Quote goes

public void init()
   {
   	try {
   		readQuotes();
   	}
   	catch(IOException e)  {
			////System.out.println("Error: "+e);
			System.exit(1);
		}
		catch(InterruptedException e)  {
			////System.out.println("Error: "+e);
			System.exit(1);
		}

		// Gets the parameters
      color();         //sets Font Color
      bgColor();       //Sets background Color
      font();          //Gets Font Characteristics
   }

   public void paint(Graphics g)
   {
   	//Set Variables
      int x = 0, y = 0;     //Coordinates for drawing the text
      int clientWidth = 5, clientHeight = 5;     //Keep the drawing area dimensions
      Font f = new Font(fontType, Font.BOLD, font_size);  //Declares font
      Dimension d = getSize();          // Size of applet

      Insets in = getInsets();         // Measures border
      clientWidth = (d.width - in.right - in.left);  //Determines actual drawing area width
      clientHeight = (d.height - in.top - in.bottom);   //Determines actual drawing area height

      g.setColor(backGroundColor);                 //Sets Background color
      g.fillRect(0, 0, getSize().width, getSize().height); //Draws background color

      g.setFont(f);              //iniatilizes font
      g.setColor(font_color);    //Sets Font to chosen Color
      FontMetrics fm = g.getFontMetrics();    //Gets FontMetrics, to measure the strings

		//If did not get a quote from the file use the default quote
		if(quote == "" || quote == null)  {
			quote = bakQuote;
			author = bakAuthor;
		}

		//Splits the quote up into the individual lines
      tokenize(g, clientWidth, clientHeight);  //Calls the method that breaks up the quote
                                               //into different lines that will fit in the applet
      //Reducing Font Size to fit in Applet
      while((l * fm.getHeight()) > clientHeight)  //Loops until all the lines can fit within the
      {                                         // applet.
      	//Checking to make sure the Font doesn't get too small
      	if(font_size > 8)
         	font_size--;   // Reduces the Font size by one
         else {
         	try  {
         		readQuotes();
         	}
         	catch(Exception e) {}
         	font();
         	update(g);
         }
         f = new Font(fontType, Font.BOLD, font_size);  //Sets the font to the new Size
         g.setFont(f);                            //Tell the graphics to use new font size
         fm = g.getFontMetrics();                 //Measures new font size
         tokenize(g, clientWidth, clientHeight);  //Calls Tokenize to readjust lines with the
      }                                           //new font size

      y = (clientHeight - (l * fm.getHeight())) / 2 + (fm.getHeight() / 2); //Centers the Text Vertically
      for(int z = 0; z <= l; z++ )     //Loop to print out the lines of the quote
      {
         x = (clientWidth - fm.stringWidth(line[z])) / 2;   //Gets x coord. to center line Horizontly
         g.drawString(line[z], x, y);     //Draws one line of the quote
         y += f.getSize();        //Moves the y coord. down the height of the font
      }
   }


   public void update(Graphics g)
   {

      paint(g);
   }




   private void readQuotes() throws IOException, InterruptedException, NoSuchElementException {
		try  {
			URL urlQuotes = new URL(getCodeBase() + strFile);
			int lineNumber = 0;  //The current Line Number
			String line = "";
			InputStreamReader isr = new InputStreamReader(urlQuotes.openStream());
			BufferedReader brFile = new BufferedReader(isr);
			if(brFile.ready())
				line = brFile.readLine();
			else {
				//System.out.println("File not Ready!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				boolean readFile = false;
				while(readFile == false)  {
					//System.out.println("In while of file not ready!!!!!!!");
					Thread.sleep(1000);
					int j = 0;
					if(brFile.ready())  {
						line = brFile.readLine();
						readFile = true;
					}
					else  {
						//System.out.println("File not Ready Again??????????????????????????");
						j++;
					}
					if(j == 100)
						readFile = true;
				}

			}

			int numberOfQuotes = Integer.parseInt(line.trim());

			int quoteNumber = (int)((Math.random() * 10000000 % numberOfQuotes)) + 1;   //Generating random starting point
			while((line = brFile.readLine()) != null)  {
				lineNumber++;
				if(lineNumber == quoteNumber)  {
					brFile.close();
					quote = line.substring(0, line.indexOf("||"));
					author = line.substring((line.indexOf("||") + 2));
					brFile.close();
					isr.close();
					return;
				}
			}
			brFile.close();
			isr.close();
		}
		catch(IOException e)  {
			////System.out.println("Error: "+e);
			System.exit(1);
		}
   }

  public void tokenize(Graphics g, int clientWidth,int clientHeight)
  {
      String SingleLine = "";  //String to keep the line that is being worked on
      String word = "";        //String to keep the next word.
      FontMetrics fm = g.getFontMetrics();  //Getting Font measurements
      int space = fm.stringWidth(" ");           // Gets the width of one space
      l = 0;          //Counter to keep track of the number of lines in the quote

      for(StringTokenizer t = new StringTokenizer(quote); t.hasMoreTokens();) //Loops until there are no more words
      {  //Splits the string into words.
         word = t.nextToken();      //Sets word equal to the next word in the quote
         int w = fm.stringWidth(word) + space;  // Gets the length of the word plus a space
         int lw = fm.stringWidth(SingleLine);  // Gets the length of the line

         if(t.hasMoreTokens())                //Checks to see if there are any more words in the string
         {

            if(lw + w > (clientWidth - 10))         //Checks to see if adding the word to the line would
            {                                       //make it longer than the applet width.

               line[l] = SingleLine;
               l++;              //Starts a new line in the quote
               SingleLine = word + " ";      //Adds the last word to the new line
            }
            else
            {

               SingleLine += " " + word;    //Adds the next word onto the current line of text
            }

         }
         else
         {

         	if(lw + w > (clientWidth - 10))         //Checks to see if adding the word to the line would
            {                                       //make it longer than the applet width.
               line[l] = SingleLine;
               l++;                    //Starts a new line in the quote
               line[l] = word + "";     //Adds the last word to the new line
            }
            else
            {
         		SingleLine = SingleLine + " " + word;  //Adds the next word onto the current line of text
         		line[l] = SingleLine;
      		}
      	}
      }

      l++;
      SingleLine = "--";
      //Checking Author to see if it fits
      for(StringTokenizer t = new StringTokenizer(author); t.hasMoreTokens();) //Loops until there are no more words
      {  //Splits the string into words.
         word = t.nextToken();      //Sets word equal to the next word in the quote
         int w = fm.stringWidth(word) + space;  // Gets the length of the word plus a space
         int lw = fm.stringWidth(SingleLine);  // Gets the length of the line

         if(t.hasMoreTokens())                //Checks to see if there are any more words in the string
         {
            if(lw + w > (clientWidth - 10))         //Checks to see if adding the word to the line would
            {                                       //make it longer than the applet width.

               line[l] = SingleLine;
               l++;              //Starts a new line in the quote
               SingleLine = word + " ";      //Adds the last word to the new line
            }
            else
            {
               SingleLine += word + " ";    //Adds the next word onto the current line of text
            }

         }
         else
         {

         	if(lw + w > (clientWidth - 10))         //Checks to see if adding the word to the line would
            {                                       //make it longer than the applet width.
               line[l] = SingleLine;
               l++;                    //Starts a new line in the quote
               line[l] = word + "";     //Adds the last word to the new line
            }
            else
            {
         		SingleLine = SingleLine + " " + word;  //Adds the next word onto the current line of text
         		line[l] = SingleLine;
      		}

      	}
      }
   }

   public void font()
   {  //Sets the Font type from params.
      String fontList[];
      String font;
      int i;

      if(getParameter("font_size") != null)
      {
         font_size = Integer.parseInt(getParameter("font_size"));
      }
      else
      {
         font_size = 18;
      }


      font =  getParameter("font");
      if(font == null)
      {
         fontType ="TimesRoman";
      }
      else
      {
         fontList = getToolkit().getFontList();  //Gets the list of font types

         for(i = 0; i < fontList.length; i++)
         {
            if(font.equalsIgnoreCase(fontList[i]))
            {
               fontType = fontList[i];
               break;
            }
         }
         if(i == fontList.length);
         {
            fontType = "TimesRoman";
         }
      }
   }


   public void color()
   {  //Sets the font Color from params
      String color = getParameter("color");  //Getting Font color from params.
      if(color == null || color.equalsIgnoreCase("black"))
      {
      font_color = Color.black;
      }
      else if(color.equalsIgnoreCase("white"))
      {
         font_color = Color.white;
      }
      else if(color.equalsIgnoreCase("lightGray"))
      {
         font_color = Color.lightGray;
      }
      else if(color.equalsIgnoreCase("gray"))
      {
         font_color = Color.gray;
      }
      else if(color.equalsIgnoreCase("darkGray"))
      {
         font_color = Color.darkGray;
      }
      else if(color.equalsIgnoreCase("red"))
      {
         font_color = Color.red;
      }
      else if(color.equalsIgnoreCase("pink"))
      {
         font_color = Color.pink;
      }
      else if(color.equalsIgnoreCase("orange"))
      {
         font_color = Color.orange;
      }
      else if(color.equalsIgnoreCase("yellow"))
      {
         font_color = Color.yellow;
      }
      else if(color.equalsIgnoreCase("green"))
      {
         font_color = Color.green;
      }
      else if(color.equalsIgnoreCase("magenta"))
      {
         font_color = Color.magenta;
      }
      else if(color.equalsIgnoreCase("cyan"))
      {
         font_color = Color.cyan;
      }
      else if(color.equalsIgnoreCase("blue"))
      {
         font_color = Color.blue;
      }
      else
      {
         font_color = Color.black;
      }
   }

public void bgColor()
   {  //Sets the background color from params
      String color = getParameter("bgcolor");  //Getting back ground color color from params.
      if(color == null || color.equalsIgnoreCase("white"))
      {
         backGroundColor = Color.white;
      }
      else if(color.equalsIgnoreCase("black"))
      {
         backGroundColor = Color.black;
      }
      else if(color.equalsIgnoreCase("lightGray"))
      {
         backGroundColor = Color.lightGray;
      }
      else if(color.equalsIgnoreCase("gray"))
      {
         backGroundColor = Color.gray;
      }
      else if(color.equalsIgnoreCase("darkGray"))
      {
        backGroundColor = Color.darkGray;
      }
      else if(color.equalsIgnoreCase("red"))
      {
         backGroundColor = Color.red;
      }
      else if(color.equalsIgnoreCase("pink"))
      {
         backGroundColor = Color.pink;
      }
      else if(color.equalsIgnoreCase("orange"))
      {
         backGroundColor = Color.orange;
      }
      else if(color.equalsIgnoreCase("yellow"))
      {
         backGroundColor = Color.yellow;
      }
      else if(color.equalsIgnoreCase("green"))
      {
         backGroundColor = Color.green;
      }
      else if(color.equalsIgnoreCase("magenta"))
      {
         backGroundColor = Color.magenta;
      }
      else if(color.equalsIgnoreCase("cyan"))
      {
         backGroundColor = Color.cyan;
      }
      else if(color.equalsIgnoreCase("blue"))
      {
         backGroundColor = Color.blue;
      }
      else
      {
         backGroundColor = Color.white;
      }
   }

	public String getAppletInfo() {
   	return "Pet Quote Applet by SimplyPets http://www.simplypets.com/";
   }

	public boolean mouseDown (Event me, int x, int y) {
		try {
			if (this.getAppletContext () != null)
				this.getAppletContext ().showDocument (new URL (urlString));
		}
		catch (Exception e) {}
		return true;
	}

   public static void main(java.lang.String[] args) throws IOException, InterruptedException {
		PetQuotes petQuotes = new PetQuotes();
			petQuotes.init();
	}
 }

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 DevX Skillbuilding from IBM developerWorks
 RIA Run Contest: Build Next-Gen Apps in Microsoft Silverlight 2
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

RIM Ups Ante With Mobile Software Push
Novell Readies Silverlight Clone for Linux
Yahoo Pitches The 'Next Generation of Search'
Alfresco's Latest ECM: Prying Open a Sector?
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads for the JON 2.0
Out with the Old, in with the New at JavaOne
Trolltech Expands WebKit Footprint

Create Secure Java Applications Productively, Part 1: Use Rational Application Developer and Data Studio
.NET Building Blocks: Custom User Control Fundamentals
Secure Internet File-Sharing with PHP, MySQL, and JavaScript
Getting Started with TBB on Windows
Moving to VoIP: Should You Go It Alone?
Introduction to the WPF Command Framework
7.0, Microsoft's Lucky Version?
Will Hyper-V Make VMware This Decade's Netscape?
Eliminate Fragmentation Frustration with Netbiscuits
Taming Trees: Building Branching Structures

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES