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.

 Avaya DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 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%.

Is .NET on Linux Finally Ready?
Red Hat Takes on HPC Market, Microsoft
Python's New Release Bridges the Gap
No Flash Seen on iPhone Horizon
Apple Yields to Complaints Over iPhone NDA
Microsoft Shows Some Ankle With Visual Studio
Gentoo Linux Cancels Distribution
It's Official: Windows 7 at PDC, WinHEC
Oracle Keeps Building on Spoils From BEA
Intel, Oracle Head For 'The Cloud'

C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild
eCryptfs: Single-File Encryption in Linux
CCXML in Action: A CCXML Auto Attendant
Ballmer: Current Woes Won't Halt Tech, Microsoft
Microsoft Uses VMworld to Hype Its Hypervisor
Microsoft Charges Ahead in Virtualization
Microsoft Shows Some Ankle With Visual Studio
Top 5 Reasons to Adopt SQL Server 2008

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
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES