Java/Swing JFC/Applet

Материал из Java эксперт
Версия от 21:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

A class to allow use of the ncsa ISMAP format in java applets

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/** A class to allow use of the ncsa ISMAP format in java applets. **/ /** version 1.0 writen for Beta2 on 12/27/95 by Dan Cohn, cohnd@rpi.edu **/ /** code for n-sided polygons based on ncsa httpd code by Eric Haines **/ /** usage example:

     Ismap zones = new Ismap();
     zones.addrect("AreaA",10,10,20,20); //AreaA a rect from (10,10) to (20,20)
     zones.addcirc("AreaB",40,45,5); //AreaB a circle at (40,45) radius 5
     zones.addrect("AreaC",25,30,27,32); //AreaC another rectangle
     zones.addzone("poly AreaD 40,60 45,60 50,65 50,70 35,70")// AreaD a blob
     zones.adddefault("OtherArea");
     zones.lookup(15,15) will return "AreaA" as (15,15) falls in that region.
     zones.lookup(100,100) will return "OtherArea", as an undefined point. **/

/** ISMAP compliant map files may also be loaded by url reference in the

   constructor or by loadmap() or addmap(). Note that files must not have .map
   extensions to be passed by the server. **/

import java.io.InputStream; import java.net.URL; public final class Ismap {

 /** rather than consulting the server, we will buffer file locally * */
 private String mapdetail[];
 /** default case if all else fails * */
 private String Default;
 /** position to offset from given values when computing area * */
 private int xoffset, yoffset;
 /** keep track of number of lines in our definitions file * */
 private int numlines;
 /** result string when match is found * */
 protected String result;
 /** number of lines available per map file. reduce for memory conservancy * */
 protected int MAXLINES = 512;
 protected int MAXVERTS = 128;
 /** generic constructor allocates mapdetail and sets offsets to 0 * */
 public Ismap() {
   this.mapdetail = new String[MAXLINES];
   this.xoffset = this.yoffset = 0;
   this.numlines = 0;
 }
 /** constructs a new Ismap which starts off by loading a url as map data * */
 public Ismap(String mapurl) {
   this.mapdetail = new String[MAXLINES];
   this.xoffset = this.yoffset = 0;
   this.loadmap(mapurl);
 }
 /** and one more constructor to start off with a url map and an x,y offset */
 public Ismap(String mapurl, int xoffset, int yoffset) {
   this.mapdetail = new String[MAXLINES];
   this.xoffset = xoffset;
   this.yoffset = yoffset;
   this.loadmap(mapurl);
 }
 public void clearmap() {
   this.numlines = 0;
 }
 public boolean loadmap(String mapurl) {
   this.numlines = 0;
   return (this.addmap(mapurl));
 }
 public boolean addmap(String mapurl) {
   int linepos = 1;
   int streambyte;
   char localln[] = new char[80];
   try {
     URL remotemap = new URL(mapurl);
     InputStream mapis = remotemap.openStream();
     do {
       streambyte = mapis.read();
       localln[linepos - 1] = (char) streambyte;
       if (localln[linepos - 1] == "\n") {
         this.mapdetail[numlines] = String.copyValueOf(localln, 0,
             linepos - 1);
         numlines++;
         linepos = 0;
       }
       linepos++;
     } while (streambyte != -1);
   } catch (java.net.MalformedURLException e) {
     System.out.println("Malformed URL! exception");
     return (false);
   } catch (java.io.IOException e) {
     System.out.println("Error reading from URL! exception");
     return (false);
   }
   return true;
 }
 public void offset(int x, int y) {
   this.xoffset = x;
   this.yoffset = y;
 }
 private boolean checkline(int testx, int testy, String thisstr) {
   int i1, i2, coordnum;
   String type, name, scoordpair;
   int coordpair[][] = new int[MAXVERTS][2];
   thisstr.trim(); /* cut any excess whitspace */
   if ((!thisstr.startsWith("#")) && (thisstr.length() > 1)) {
     i1 = thisstr.indexOf(" ");
     type = thisstr.substring(0, i1);
     if (!type.equals("default"))
       i2 = thisstr.indexOf(" ", i1 + 1);
     else { /* default case */
       this.Default = thisstr.substring(i1 + 1);
       return false;
     }
     name = thisstr.substring(i1 + 1, i2);
     i1 = i2;
     i2 = thisstr.indexOf(" ", i1 + 1);
     for (coordnum = 0; i2 != -1; coordnum++) {
       scoordpair = thisstr.substring(i1 + 1, i2);
       coordpair[coordnum][0] = Integer.valueOf(
           scoordpair.substring(0, scoordpair.indexOf(",")))
           .intValue();
       coordpair[coordnum][1] = Integer.valueOf(
           scoordpair.substring(scoordpair.indexOf(",") + 1))
           .intValue();
       i1 = i2;
       i2 = thisstr.indexOf(" ", i1 + 1);
       if ((i2 == -1) && (i1 != thisstr.length()))
         i2 = thisstr.length();
     }
     coordpair[coordnum][0] = -1; // end of pairs sentinel for polygon
     // code
     if (type.equals("rect"))
       if (pointinrect(testx, testy, coordpair)) {
         this.result = name;
         return true;
       }
     if (type.equals("circ"))
       if (pointincirc(testx, testy, coordpair)) {
         this.result = name;
         return true;
       }
     if (type.equals("poly"))
       if (pointinpoly(testx, testy, coordpair)) {
         this.result = name;
         return true;
       }
   }
   return false; // not within boundaries of this line
 }
 public String lookup(int xcoord, int ycoord) {
   int linecount = 0;
   xcoord += this.xoffset;
   ycoord += this.yoffset;
   for (linecount = 0; linecount < numlines; linecount++) {
     if (checkline(xcoord, ycoord, String
         .valueOf(this.mapdetail[linecount])))
       return (this.result);
   }
   if (this.Default.length() > 0)
     return (this.Default);
   System.out.println("The point (" + xcoord + "," + ycoord
       + ") has not been "
       + "accounted for and no default was defined.");
   return ("");
 }
 public void dumpmap() {
   int linecount = 0;
   for (linecount = 0; linecount < numlines; linecount++) {
     System.out.println(String.valueOf(mapdetail[linecount]));
   }
 }
 public void addzone(String mapinfo) {
   this.mapdetail[numlines++] = mapinfo;
 }
 public void adddefault(String regionname) {
   this.mapdetail[numlines++] = "default " + regionname;
 }
 public void addrect(String regionname, int x1, int y1, int x2, int y2) {
   this.mapdetail[numlines++] = "rect " + regionname + " " + x1 + "," + y1
       + " " + x2 + "," + y2;
 }
 public void addcirc(String regionname, int x1, int y1, int r) {
   int outerpt = x1 + r;
   this.mapdetail[numlines++] = "circ " + regionname + " " + x1 + "," + y1
       + " " + outerpt + "," + y1;
 }
 private boolean pointinrect(int x, int y, int coords[][]) {
   return ((x >= coords[0][0] && x <= coords[1][1]) && (y >= coords[0][1] && y <= coords[1][1]));
 }
 private boolean pointincirc(int x, int y, int coords[][]) {
   int radius1, radius2;
   radius1 = ((coords[0][1] - coords[1][1]) * (coords[0][1] - coords[1][1]))
       + ((coords[0][0] - coords[1][0]) * (coords[0][0] - coords[1][0]));
   radius2 = ((coords[0][1] - y) * (coords[0][1] - y))
       + ((coords[0][0] - x) * (coords[0][0] - x));
   return (radius2 <= radius1);
 }
 private boolean pointinpoly(int tx, int ty, int pgon[][]) {
   int i, numverts, inside_flag, crossings;
   boolean xflag0;
   double stop, y;
   for (i = 0; pgon[i][0] != -1 && i < MAXVERTS; i++)
     ;
   numverts = i;
   crossings = 0;
   y = pgon[numverts - 1][1];
   if ((y >= ty) != (pgon[0][1] >= ty)) {
     if ((xflag0 = (pgon[numverts - 1][0] >= tx)) == (pgon[0][0] >= tx)) {
       if (xflag0)
         crossings++;
     } else {
       if ((pgon[numverts - 1][0] - (y - ty)
           * (pgon[0][0] - pgon[numverts - 1][0])
           / (pgon[0][1] - y)) >= tx)
         crossings++;
     }
   }
   stop = numverts;
   for (int index = 1; index < stop; y = pgon[index][1], index++) {
     if (y >= ty) {
       while ((index < stop) && (pgon[index][1] >= ty))
         index++;
       if (index >= stop)
         break;
       if ((xflag0 = (pgon[index - 1][0] >= tx)) == (pgon[index][0] >= tx)) {
         if (xflag0)
           crossings++;
       } else {
         if ((pgon[index - 1][0] - (pgon[index - 1][1] - ty)
             * (pgon[index][0] - pgon[index - 1][0])
             / (pgon[index][1] - pgon[index - 1][1])) >= tx)
           crossings++;
       }
     } else {
       while ((index < stop) && (pgon[index][1] < ty))
         index++;
       if (index >= stop)
         break;
       if ((xflag0 = (pgon[index - 1][0] >= tx)) == (pgon[index][0] >= tx)) {
         if (xflag0)
           crossings++;
       } else {
         if ((pgon[index - 1][0] - (pgon[index - 1][1] - ty)
             * (pgon[index][0] - pgon[index - 1][0])
             / (pgon[index][1] - pgon[index - 1][1])) >= tx)
           crossings++;
       }
     }
   }
   inside_flag = crossings & 0x01;
   return (inside_flag > 0);
 }

}


 </source>
   
  
 
  



An application and an applet

   <source lang="java">
 

// : c14:Applet1c.java // An application and an applet. // <applet code=Applet1c width=100 height=50></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JLabel; public class Applet1c extends JApplet {

 public void init() {
   getContentPane().add(new JLabel("Applet!"));
 }
 // A main() for the application:
 public static void main(String[] args) {
   JApplet applet = new Applet1c();
   JFrame frame = new JFrame("Applet1c");
   // To close the application:
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(100, 50);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~



 </source>
   
  
 
  



Applet and Swing Components

   <source lang="java">
 

// : c14:List.java // <applet code=List width=250 height=375></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JTextArea; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class List extends JApplet {

 private String[] flavors = { "Chocolate", "Strawberry",
     "Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge",
     "Rum Raisin", "Praline Cream", "Mud Pie" };
 private DefaultListModel lItems = new DefaultListModel();
 private JList lst = new JList(lItems);
 private JTextArea t = new JTextArea(flavors.length, 20);
 private JButton b = new JButton("Add Item");
 private ActionListener bl = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     if (count < flavors.length) {
       lItems.add(0, flavors[count++]);
     } else {
       // Disable, since there are no more
       // flavors left to be added to the List
       b.setEnabled(false);
     }
   }
 };
 private ListSelectionListener ll = new ListSelectionListener() {
   public void valueChanged(ListSelectionEvent e) {
     if (e.getValueIsAdjusting())
       return;
     t.setText("");
     Object[] items = lst.getSelectedValues();
     for (int i = 0; i < items.length; i++)
       t.append(items[i] + "\n");
   }
 };
 private int count = 0;
 public void init() {
   Container cp = getContentPane();
   t.setEditable(false);
   cp.setLayout(new FlowLayout());
   // Create Borders for components:
   Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.BLACK);
   lst.setBorder(brd);
   t.setBorder(brd);
   // Add the first four items to the List
   for (int i = 0; i < 4; i++)
     lItems.addElement(flavors[count++]);
   // Add items to the Content Pane for Display
   cp.add(t);
   cp.add(lst);
   cp.add(b);
   // Register event listeners
   lst.addListSelectionListener(ll);
   b.addActionListener(bl);
 }
 public static void main(String[] args) {
   run(new List(), 250, 375);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~



 </source>
   
  
 
  



Applet clock demo

   <source lang="java">
 

//File: applet.html /* <applet code="ClockDemo.class"

 codebase="."
 width=150 height=20>

</applet>

  • /

/// /*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Font; import java.awt.Label; import java.text.DateFormat; import java.util.Date; /**

* This applet displays the time, and updates it every second
*/

public class ClockDemo extends Applet implements Runnable {

 Label time; // A component to display the time in
 DateFormat timeFormat; // This object converts the time to a string
 Thread timer; // The thread that updates the time
 volatile boolean running; // A flag used to stop the thread
 /**
  * The init method is called when the browser first starts the applet. It
  * sets up the Label component and obtains a DateFormat object
  */
 public void init() {
   time = new Label();
   time.setFont(new Font("helvetica", Font.BOLD, 12));
   time.setAlignment(Label.CENTER);
   setLayout(new BorderLayout());
   add(time, BorderLayout.CENTER);
   timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
 }
 /**
  * This browser calls this method to tell the applet to start running. Here,
  * we create and start a thread that will update the time each second. Note
  * that we take care never to have more than one thread
  */
 public void start() {
   running = true; // Set the flag
   if (timer == null) { // If we don"t already have a thread
     timer = new Thread(this); // Then create one
     timer.start(); // And start it running
   }
 }
 /**
  * This method implements Runnable. It is the body of the thread. Once a
  * second, it updates the text of the Label to display the current time
  */
 public void run() {
   while (running) { // Loop until we"re stopped
     // Get current time, convert to a String, and display in the Label
     time.setText(timeFormat.format(new Date()));
     // Now wait 1000 milliseconds
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
     }
   }
   // If the thread exits, set it to null so we can create a new one
   // if start() is called again.
   timer = null;
 }
 /**
  * The browser calls this method to tell the applet that it is not visible
  * and should not run. It sets a flag that tells the run() method to exit
  */
 public void stop() {
   running = false;
 }
 /**
  * Returns information about the applet for display by the applet viewer
  */
 public String getAppletInfo() {
   return "Clock applet Copyright (c) 2000 by David Flanagan";
 }

}


 </source>
   
  
 
  



Applet communication (talk to each other)

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

<applet code=Sender.class width=450 height=200

name="buddy">

<param name="receiverName" value="old pal"> </applet>

<applet code=Receiver.class width=450 height=35> <param name="name" value="old pal"> </applet> <applet code=GetApplets.class width=400 height=150> </applet> /* * 1.1 version. */ import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.Enumeration; public class Sender extends Applet implements ActionListener { private String myName; private TextField nameField; private TextArea status; private String newline; public void init() { GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridBag); Label receiverLabel = new Label("Receiver name:", Label.RIGHT); gridBag.setConstraints(receiverLabel, c); add(receiverLabel); nameField = new TextField(getParameter("RECEIVERNAME"), 10); c.fill = GridBagConstraints.HORIZONTAL; gridBag.setConstraints(nameField, c); add(nameField); nameField.addActionListener(this); Button button = new Button("Send message"); c.gridwidth = GridBagConstraints.REMAINDER; //end row c.anchor = GridBagConstraints.WEST; //stick to the //text field c.fill = GridBagConstraints.NONE; //keep the button //small gridBag.setConstraints(button, c); add(button); button.addActionListener(this); status = new TextArea(5, 60); status.setEditable(false); c.anchor = GridBagConstraints.CENTER; //reset to the default c.fill = GridBagConstraints.BOTH; //make this big c.weightx = 1.0; c.weighty = 1.0; gridBag.setConstraints(status, c); add(status); myName = getParameter("NAME"); Label senderLabel = new Label("(My name is " + myName + ".)", Label.CENTER); c.weightx = 0.0; c.weighty = 0.0; gridBag.setConstraints(senderLabel, c); add(senderLabel); newline = System.getProperty("line.separator"); } public void actionPerformed(ActionEvent event) { Applet receiver = null; String receiverName = nameField.getText(); //Get name to //search for. receiver = getAppletContext().getApplet(receiverName); if (receiver != null) { //Use the instanceof operator to make sure the applet //we found is a Receiver object. if (!(receiver instanceof Receiver)) { status.append("Found applet named " + receiverName + ", " + "but it"s not a Receiver object." + newline); } else { status.append("Found applet named " + receiverName + newline + " Sending message to it." + newline); //Cast the receiver to be a Receiver object //(instead of just an Applet object) so that the //compiler will let us call a Receiver method. ((Receiver)receiver).processRequestFrom(myName); } } else { status.append("Couldn"t find any applet named " + receiverName + "." + newline); } } public Insets getInsets() { return new Insets(3,3,3,3); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); } public String getAppletInfo() { return "Sender by Kathy Walrath"; } } /* * 1.1 version. */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class Receiver extends Applet implements ActionListener { private final String waitingMessage = "Waiting for a message... "; private Label label = new Label(waitingMessage, Label.RIGHT); public void init() { Button button = new Button("Clear"); add(label); add(button); button.addActionListener(this); add(new Label("(My name is " + getParameter("name") + ".)", Label.LEFT)); } public void actionPerformed(ActionEvent event) { label.setText(waitingMessage); } public void processRequestFrom(String senderName) { label.setText("Received message from " + senderName + "!"); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); } public String getAppletInfo() { return "Receiver (named " + getParameter("name") + ") by Kathy Walrath"; } } </source>

Applet event tester

   <source lang="java">
 

//File: applet.html /* <applet code="EventTester.class"

 codebase="."
 width=400 height=400>

</applet>

  • /

/// /*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.applet.Applet; import java.awt.Event; import java.awt.Graphics; import java.util.Vector; /** An applet that gives details about Java 1.0 events */ public class EventTester extends Applet {

 // Handle mouse events
 public boolean mouseDown(Event e, int x, int y) {
   showLine(mods(e.modifiers) + "Mouse Down: [" + x + "," + y + "]");
   return true;
 }
 public boolean mouseUp(Event e, int x, int y) {
   showLine(mods(e.modifiers) + "Mouse Up: [" + x + "," + y + "]");
   return true;
 }
 public boolean mouseDrag(Event e, int x, int y) {
   showLine(mods(e.modifiers) + "Mouse Drag: [" + x + "," + y + "]");
   return true;
 }
 public boolean mouseMove(Event e, int x, int y) {
   showLine(mods(e.modifiers) + "Mouse Move: [" + x + "," + y + "]");
   return true;
 }
 public boolean mouseEnter(Event e, int x, int y) {
   showLine("Mouse Enter: [" + x + "," + y + "]");
   return true;
 }
 public boolean mouseExit(Event e, int x, int y) {
   showLine("Mouse Exit: [" + x + "," + y + "]");
   return true;
 }
 // Handle focus events
 public boolean gotFocus(Event e, Object what) {
   showLine("Got Focus");
   return true;
 }
 public boolean lostFocus(Event e, Object what) {
   showLine("Lost Focus");
   return true;
 }
 // Handle key down and key up events
 // This gets more confusing because there are two types of key events
 public boolean keyDown(Event e, int key) {
   int flags = e.modifiers;
   if (e.id == Event.KEY_PRESS) // a regular key
     showLine("Key Down: " + mods(flags) + key_name(e));
   else if (e.id == Event.KEY_ACTION) // a function key
     showLine("Function Key Down: " + mods(flags)
         + function_key_name(key));
   return true;
 }
 public boolean keyUp(Event e, int key) {
   int flags = e.modifiers;
   if (e.id == Event.KEY_RELEASE) // a regular key
     showLine("Key Up: " + mods(flags) + key_name(e));
   else if (e.id == Event.KEY_ACTION_RELEASE) // a function key
     showLine("Function Key Up: " + mods(flags) + function_key_name(key));
   return true;
 }
 // The remaining methods help us sort out the various modifiers and keys
 // Return the current list of modifier keys
 private String mods(int flags) {
   String s = "[ ";
   if (flags == 0)
     return "";
   if ((flags & Event.SHIFT_MASK) != 0)
     s += "Shift ";
   if ((flags & Event.CTRL_MASK) != 0)
     s += "Control ";
   if ((flags & Event.META_MASK) != 0)
     s += "Meta ";
   if ((flags & Event.ALT_MASK) != 0)
     s += "Alt ";
   s += "] ";
   return s;
 }
 // Return the name of a regular (non-function) key.
 private String key_name(Event e) {
   char c = (char) e.key;
   if (e.controlDown()) { // If CTRL flag is set, handle control chars.
     if (c < " ") {
       c += "@";
       return "^" + c;
     }
   } else { // If CTRL flag is not set, then certain ASCII
     switch (c) { // control characters have special meaning.
     case "\n":
       return "Return";
     case "\t":
       return "Tab";
     case "\033":
       return "Escape";
     case "\010":
       return "Backspace";
     }
   }
   // Handle the remaining possibilities.
   if (c == "\177")
     return "Delete";
   else if (c == " ")
     return "Space";
   else
     return String.valueOf(c);
 }
 // Return the name of a function key. Just compare the key to the
 // constants defined in the Event class.
 private String function_key_name(int key) {
   switch (key) {
   case Event.HOME:
     return "Home";
   case Event.END:
     return "End";
   case Event.PGUP:
     return "Page Up";
   case Event.PGDN:
     return "Page Down";
   case Event.UP:
     return "Up";
   case Event.DOWN:
     return "Down";
   case Event.LEFT:
     return "Left";
   case Event.RIGHT:
     return "Right";
   case Event.F1:
     return "F1";
   case Event.F2:
     return "F2";
   case Event.F3:
     return "F3";
   case Event.F4:
     return "F4";
   case Event.F5:
     return "F5";
   case Event.F6:
     return "F6";
   case Event.F7:
     return "F7";
   case Event.F8:
     return "F8";
   case Event.F9:
     return "F9";
   case Event.F10:
     return "F10";
   case Event.F11:
     return "F11";
   case Event.F12:
     return "F12";
   }
   return "Unknown Function Key";
 }
 /** A list of lines to display in the window */
 protected Vector lines = new Vector();
 /** Add a new line to the list of lines, and redisplay */
 protected void showLine(String s) {
   if (lines.size() == 20)
     lines.removeElementAt(0);
   lines.addElement(s);
   repaint();
 }
 /** This method repaints the text in the window */
 public void paint(Graphics g) {
   for (int i = 0; i < lines.size(); i++)
     g.drawString((String) lines.elementAt(i), 20, i * 16 + 50);
 }

}


 </source>
   
  
 
  



Applet Menu Bar Demo

   <source lang="java">
 

/*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.applet.Applet; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Panel; import java.awt.PopupMenu; import java.awt.event.MouseEvent; import java.util.Vector; public class AppletMenuBarDemo extends Applet {

 public void init() {
   AppletMenuBar menubar = new AppletMenuBar();
   menubar.setForeground(Color.black);
   menubar.setHighlightColor(Color.red);
   menubar.setFont(new Font("helvetica", Font.BOLD, 12));
   this.setLayout(new BorderLayout());
   this.add(menubar, BorderLayout.NORTH);
   PopupMenu file = new PopupMenu();
   file.add("New...");
   file.add("Open...");
   file.add("Save As...");
   PopupMenu edit = new PopupMenu();
   edit.add("Cut");
   edit.add("Copy");
   edit.add("Paste");
   menubar.addMenu("File", file);
   menubar.addMenu("Edit", edit);
 }

} /*

* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/

class AppletMenuBar extends Panel {

 // Menubar contents
 Vector labels = new Vector();
 Vector menus = new Vector();
 // Properties
 Insets margins = new Insets(3, 10, 3, 10); // top, left, bottom, right
 int spacing = 10; // Space between menu labels
 Color highlightColor; // Rollover color for labels
 // internal stuff
 boolean remeasure = true; // Whether the labels need to be remeasured
 int[] widths; // The width of each label
 int[] startPositions; // Where each label starts
 int ascent, descent; // Font metrics
 Dimension prefsize = new Dimension(); // How big do we want to be?
 int highlightedItem = -1; // Which item is the mouse over?
 /**
  * Create a new component that simulates a menubar by displaying the
  * specified labels. Whenever the user clicks the specified label, popup up
  * the PopupMenu specified in the menus array. Elements of the menus arra
  * may be a static PopupMenu object, or a PopupMenuFactory object for
  * dynamically creating menus. Perhaps we"ll also provide some other kind of
  * constructor or factory method that reads popup menus out of a config
  * file.
  */
 public AppletMenuBar() {
   // We"d like these kinds of events to be delivered
   enableEvents(AWTEvent.MOUSE_EVENT_MASK
       | AWTEvent.MOUSE_MOTION_EVENT_MASK);
 }
 /** Add a popup menu to the menubar */
 public void addMenu(String label, PopupMenu menu) {
   insertMenu(label, menu, -1);
 }
 /** Insert a popup menu into the menubar */
 public void insertMenu(String label, PopupMenu menu, int index) {
   if (index < 0)
     index += labels.size() + 1; // Position to put it at
   this.add(menu); // Popup belongs to us
   labels.insertElementAt(label, index); // Remember the label
   menus.insertElementAt(menu, index); // Remember the menu
   remeasure = true; // Remeasure everything
   invalidate(); // Container must relayout
 }
 /** Property accessor methods for margins property */
 public Insets getMargins() {
   return (Insets) margins.clone();
 }
 public void setMargins(Insets margins) {
   this.margins = margins;
   remeasure = true;
   invalidate();
 }
 /** Property accessor methods for spacing property */
 public int getSpacing() {
   return spacing;
 }
 public void setSpacing(int spacing) {
   if (this.spacing != spacing) {
     this.spacing = spacing;
     remeasure = true;
     invalidate();
   }
 }
 /** Accessor methods for highlightColor property */
 public Color getHighlightColor() {
   if (highlightColor == null)
     return getForeground();
   else
     return highlightColor;
 }
 public void setHighlightColor(Color c) {
   if (highlightColor != c) {
     highlightColor = c;
     repaint();
   }
 }
 /** We override the setFont() method so we can remeasure */
 public void setFont(Font f) {
   super.setFont(f);
   remeasure = true;
   invalidate();
 }
 /** Override these color property setter method so we can repaint */
 public void setForeground(Color c) {
   super.setForeground(c);
   repaint();
 }
 public void setBackground(Color c) {
   super.setBackground(c);
   repaint();
 }
 /**
  * This method is called to draw tell the component to redraw itself. If we
  * were implementing a Swing component, we"d override paintComponent()
  * instead
  */
 public void paint(Graphics g) {
   if (remeasure)
     measure(); // Remeasure everything first, if needed
   // Figure out Y coordinate to draw at
   Dimension size = getSize();
   int baseline = size.height - margins.bottom - descent;
   // Set the font to draw with
   g.setFont(getFont());
   // Loop through the labels
   int nummenus = labels.size();
   for (int i = 0; i < nummenus; i++) {
     // Set the drawing color. Highlight the current item
     if ((i == highlightedItem) && (highlightColor != null))
       g.setColor(getHighlightColor());
     else
       g.setColor(getForeground());
     // Draw the menu label at the position computed in measure()
     g.drawString((String) labels.elementAt(i), startPositions[i],
         baseline);
   }
   // Now draw a groove at the bottom of the menubar.
   Color bg = getBackground();
   g.setColor(bg.darker());
   g.drawLine(0, size.height - 2, size.width, size.height - 2);
   g.setColor(bg.brighter());
   g.drawLine(0, size.height - 1, size.width, size.height - 1);
 }
 /** Called when a mouse event happens over the menubar */
 protected void processMouseEvent(MouseEvent e) {
   int type = e.getID(); // What type of event?
   int item = findItemAt(e.getX()); // Over which menu label?
   if (type == MouseEvent.MOUSE_PRESSED) {
     // If it was a mouse down event, then pop up the menu
     if (item == -1)
       return;
     Dimension size = getSize();
     PopupMenu pm = (PopupMenu) menus.elementAt(item);
     if (pm != null)
       pm.show(this, startPositions[item] - 3, size.height);
   } else if (type == MouseEvent.MOUSE_EXITED) {
     // If the mouse left the menubar, then unhighlight
     if (highlightedItem != -1) {
       highlightedItem = -1;
       if (highlightColor != null)
         repaint();
     }
   } else if ((type == MouseEvent.MOUSE_MOVED)
       || (type == MouseEvent.MOUSE_ENTERED)) {
     // If the mouse moved, change the highlighted item, if necessary
     if (item != highlightedItem) {
       highlightedItem = item;
       if (highlightColor != null)
         repaint();
     }
   }
 }
 /** This method is called when the mouse moves */
 protected void processMouseMotionEvent(MouseEvent e) {
   processMouseEvent(e);
 }
 /** This utility method converts an X coordinate to a menu label index */
 protected int findItemAt(int x) {
   // This could be a more efficient search...
   int nummenus = labels.size();
   int halfspace = spacing / 2 - 1;
   int i;
   for (i = nummenus - 1; i >= 0; i--) {
     if ((x >= startPositions[i] - halfspace)
         && (x <= startPositions[i] + widths[i] + halfspace))
       break;
   }
   return i;
 }
 /**
  * Measure the menu labels, and figure out their positions, so we can
  * determine when a click happens, and so we can redraw efficiently.
  */
 protected void measure() {
   // Get information about the font
   FontMetrics fm = this.getFontMetrics(getFont());
   // Remember the basic font size
   ascent = fm.getAscent();
   descent = fm.getDescent();
   // Create arrays to hold the measurements and positions
   int nummenus = labels.size();
   widths = new int[nummenus];
   startPositions = new int[nummenus];
   // Measure the label strings and
   // figure out the starting position of each label
   int pos = margins.left;
   for (int i = 0; i < nummenus; i++) {
     startPositions[i] = pos;
     String label = (String) labels.elementAt(i);
     widths[i] = fm.stringWidth(label);
     pos += widths[i] + spacing;
   }
   // Compute our preferred size from this data
   prefsize.width = pos - spacing + margins.right;
   prefsize.height = ascent + descent + margins.top + margins.bottom;
   // We"ve don"t need to be remeasured anymore.
   remeasure = false;
 }
 /**
  * These methods tell the container how big the menubar wants to be.
  *  
  */
 public Dimension getMinimumSize() {
   return getPreferredSize();
 }
 public Dimension getPreferredSize() {
   if (remeasure)
     measure();
   return prefsize;
 }
 /** @deprecated Here for compatibility with Java 1.0 */
 public Dimension minimumSize() {
   return getPreferredSize();
 }
 /** @deprecated Here for compatibility with Java 1.0 */
 public Dimension preferredSize() {
   return getPreferredSize();
 }
 /**
  * This method is called when the underlying AWT component is created. We
  * can"t measure ourselves (no font metrics) until this is called.
  */
 public void addNotify() {
   super.addNotify();
   measure();
 }
 /** This method tells the container not to give us keyboard focus */
 public boolean isFocusTraversable() {
   return false;
 }

}


 </source>
   
  
 
  



Applet Print

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.applet.Applet; import java.awt.GridLayout; import java.awt.TextArea; public class LamePrintThread extends Applet {

 TextArea display = new TextArea(1, 80);
 String newline;
 public void init() {
   //Create the text area and make it uneditable.
   display = new TextArea(1, 80);
   display.setEditable(false);
   //Set the layout manager so that the text area
   //will be as wide as possible.
   setLayout(new GridLayout(1, 0));
   //Add the text area to the applet.
   add(display);
   //Find the platform-dependent newline character.
   newline = System.getProperty("line.separator");
   addItem("init: " + threadInfo(Thread.currentThread()));
 }
 public void start() {
   addItem("start: " + threadInfo(Thread.currentThread()));
 }
 public void stop() {
   addItem("stop: " + threadInfo(Thread.currentThread()));
 }
 public void destroy() {
   addItem("destroy: " + threadInfo(Thread.currentThread()));
   //removeAll(); //XXXAppletViewer allows 2 init calls.
 }
 String threadInfo(Thread t) {
   return "thread=" + t.getName() + ", " + "thread group="
       + t.getThreadGroup().getName();
 }
 void addItem(String newWord) {
   System.out.println(newWord);
   display.append(newWord + newline);
   display.repaint();
 }
 //DO NOT IMPLEMENT update() and paint()! Netscape Navigator 2.0
 //for Windows (and maybe other browsers) crashes if you do.

} //File: /* <html> <title> 1.1 LamePrintThread </title> <body>

1.1 LamePrintThread (x2)

   <applet code="LamePrintThread.class" width=450 height=100>
   </applet>
   <applet code="LamePrintThread.class" width=450 height=100>
   </applet>

</body> </html>

  • /


 </source>
   
  
 
  



Applet: Print from an Applet

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.applet.Applet; import java.awt.Graphics; import java.awt.TextArea; public class PrintThread extends Applet {

 java.awt.TextArea display = new java.awt.TextArea(1, 80);
 int paintCount = 0;
 String newline;
 public void init() {
   //Create the text area and make it uneditable.
   display = new TextArea(1, 80);
   display.setEditable(false);
   //Set the layout manager so that the text area
   //will be as wide as possible.
   setLayout(new java.awt.GridLayout(1, 0));
   //Add the text area to the applet.
   add(display);
   //Find the platform-dependent newline character.
   newline = System.getProperty("line.separator");
   addItem("init: " + threadInfo(Thread.currentThread()));
 }
 public void start() {
   addItem("start: " + threadInfo(Thread.currentThread()));
 }
 public void stop() {
   addItem("stop: " + threadInfo(Thread.currentThread()));
 }
 public void destroy() {
   addItem("destroy: " + threadInfo(Thread.currentThread()));
   //removeAll(); //XXXAppletViewer allows 2 init calls.
 }
 String threadInfo(Thread t) {
   return "thread=" + t.getName() + ", " + "thread group="
       + t.getThreadGroup().getName();
 }
 void addItem(String newWord) {
   System.out.println(newWord);
   display.append(newWord + newline);
   display.repaint();
   //A hack to get the applet update() method called
   //occasionally:
   if (++paintCount % 4 == 0) {
     repaint();
   }
 }
 public void update(Graphics g) {
   addItem("update: " + threadInfo(Thread.currentThread()));
   super.update(g);
 }

} /* <html> <title> 1.1 PrintThread </title> <body>

1.1 PrintThread (x2)

   <applet code="PrintThread.class" width=450 height=100>
   </applet>
   <applet code="PrintThread.class" width=450 height=100>
   </applet>

</body> </html>

  • /


 </source>
   
  
 
  



Applet Socket Quote

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.io.*; import java.net.*; import java.util.*; class QuoteServerThread extends Thread {

   private DatagramSocket socket = null;
   private BufferedReader qfs = null;
   private boolean moreQuotes = true;
   QuoteServerThread() {
       super("QuoteServer");
       try {
           socket = new DatagramSocket();
           System.out.println("QuoteServer listening on port: " + socket.getLocalPort());
       } catch (java.io.IOException e) {
           System.err.println("Could not create datagram socket.");
       }
       this.openInputFile();
   }
   public void run() {
       if (socket == null)
           return;
       while (moreQuotes) {
           try {
               byte[] buf = new byte[256];
               DatagramPacket packet;
               InetAddress address;
               int port;
               String dString = null;
                   // receive request
               packet = new DatagramPacket(buf, 256);
               socket.receive(packet);
               address = packet.getAddress();
               port = packet.getPort();
                   // send response
               if (qfs == null)
                   dString = new Date().toString();
               else
                   dString = getNextQuote();
               buf = dString.getBytes();
               packet = new DatagramPacket(buf, buf.length, address, port);
               socket.send(packet);
           } catch (IOException e) {
               System.err.println("IOException:  " + e);
               moreQuotes = false;
               e.printStackTrace();
           }
       }
 socket.close();
   }
   private void openInputFile() {
       try {
           qfs = new BufferedReader(new InputStreamReader(new FileInputStream("one-liners.txt")));
       } catch (java.io.FileNotFoundException e) {
           System.err.println("Could not open quote file. Serving time instead.");
       }
   }
   private String getNextQuote() {
       String returnValue = null;
       try {
           if ((returnValue = qfs.readLine()) == null) {
               qfs.close();
               moreQuotes = false;
               returnValue = "No more quotes. Goodbye.";
           }
       } catch (IOException e) {
           returnValue = "IOException occurred in server.";
       }
       return returnValue;
   }

} //File: one-liners.txt /* Life is wonderful. Without it we"d all be dead. Daddy, why doesn"t this magnet pick up this floppy disk? Give me ambiguity or give me something else. I.R.S.: We"ve got what it takes to take what you"ve got! We are born naked, wet and hungry. Then things get worse. Make it idiot proof and someone will make a better idiot. He who laughs last thinks slowest! Always remember you"re unique, just like everyone else. "More hay, Trigger?" "No thanks, Roy, I"m stuffed!" A flashlight is a case for holding dead batteries. Lottery: A tax on people who are bad at math. Error, no keyboard - press F1 to continue. There"s too much blood in my caffeine system. Artificial Intelligence usually beats real stupidity. Hard work has a future payoff. Laziness pays off now. "Very funny, Scotty. Now beam down my clothes." Puritanism: The haunting fear that someone, somewhere may be happy. Consciousness: that annoying time between naps. Don"t take life too seriously, you won"t get out alive. I don"t suffer from insanity. I enjoy every minute of it. Better to understand a little than to misunderstand a lot. The gene pool could use a little chlorine. When there"s a will, I want to be in it. Okay, who put a "stop payment" on my reality check? We have enough youth, how about a fountain of SMART? Programming is an art form that fights back. "Daddy, what does FORMATTING DRIVE C mean?" All wiyht. Rho sritched mg kegtops awound? My mail reader can beat up your mail reader. Never forget: 2 + 2 = 5 for extremely large values of 2. Nobody has ever, ever, EVER learned all of WordPerfect. To define recursion, we must first define recursion. Good programming is 99% sweat and 1% coffee. Home is where you hang your @ The E-mail of the species is more deadly than the mail. A journey of a thousand sites begins with a single click. You can"t teach a new mouse old clicks. Great groups from little icons grow. Speak softly and carry a cellular phone. C:\ is the root of all directories. Don"t put all your hypes in one home page. Pentium wise; pen and paper foolish. The modem is the message. Too many clicks spoil the browse. The geek shall inherit the earth. A chat has nine lives. Don"t byte off more than you can view. Fax is stranger than fiction. What boots up must come down. Windows will never cease. (ed. oh sure...) In Gates we trust. (ed. yeah right....) Virtual reality is its own reward. Modulation in all things. A user and his leisure time are soon parted. There"s no place like http://www.home.ru Know what to expect before you connect. Oh, what a tangled website we weave when first we practice. Speed thrills. Give a man a fish and you feed him for a day; teach him to use the Net and he won"t bother you for weeks.

  • /

/*

* This is the same in 1.0 as in 1.1.
*/

class QuoteServer {

   public static void main(String[] args) {
       new QuoteServerThread().start();
   }

}

/*

* 1.1 version.
*/

import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; public class QuoteClientApplet extends Applet

                              implements ActionListener {
   boolean DEBUG = false;
   InetAddress address;
   TextField portField;
   Label display;
   DatagramSocket socket;
   public void init() {
       //Initialize networking stuff.
       String host = getCodeBase().getHost();
       try {
           address = InetAddress.getByName(host);
       } catch (UnknownHostException e) {
           System.out.println("Couldn"t get Internet address: Unknown host");
           // What should we do?
       }
       try {
           socket = new DatagramSocket();
       } catch (IOException e) {
           System.out.println("Couldn"t create new DatagramSocket");
           return;
       }
       //Set up the UI.
       GridBagLayout gridBag = new GridBagLayout();
       GridBagConstraints c = new GridBagConstraints();
       setLayout(gridBag);
       Label l1 = new Label("Quote of the Moment:", Label.CENTER);
       c.anchor = GridBagConstraints.SOUTH;
       c.gridwidth = GridBagConstraints.REMAINDER;
       gridBag.setConstraints(l1, c); 
       add(l1);
       display = new Label("(no quote received yet)", Label.CENTER);
       c.anchor = GridBagConstraints.NORTH;
       c.weightx = 1.0;
       c.fill = GridBagConstraints.HORIZONTAL;
       gridBag.setConstraints(display, c); 
       add(display);
       Label l2 = new Label("Enter the port (on host " + host
                            + ") to send the request to:", 
                            Label.RIGHT);
       c.anchor = GridBagConstraints.SOUTH;
       c.gridwidth = 1;
       c.weightx = 0.0;
       c.weighty = 1.0;
       c.fill = GridBagConstraints.NONE;
       gridBag.setConstraints(l2, c); 
       add(l2);
       portField = new TextField(6);
       gridBag.setConstraints(portField, c); 
       add(portField);
       Button button = new Button("Send");
       gridBag.setConstraints(button, c); 
       add(button);
       portField.addActionListener(this);
       button.addActionListener(this);
   }
   public Insets getInsets() {
       return new Insets(4,4,5,5);
   }
   public void paint(Graphics g) {
       Dimension d = getSize();
       Color bg = getBackground();
       g.setColor(bg);
       g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
       g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
   }
   void doIt(int port) {
       DatagramPacket packet;
       byte[] sendBuf = new byte[256];
       
       packet = new DatagramPacket(sendBuf, 256, address, port);
       try { // send request
           if (DEBUG) {
               System.out.println("Applet about to send packet to address "
                              + address + " at port " + port);
           }
           socket.send(packet);
           if (DEBUG) {
               System.out.println("Applet sent packet.");
           }
       } catch (IOException e) {
           System.out.println("Applet socket.send failed:");
           e.printStackTrace();
           return;
       }
       packet = new DatagramPacket(sendBuf, 256);
       try { // get response
           if (DEBUG) {
               System.out.println("Applet about to call socket.receive().");
           }
           socket.receive(packet);
           if (DEBUG) {
               System.out.println("Applet returned from socket.receive().");
           }
       } catch (IOException e) {
           System.out.println("Applet socket.receive failed:");
           e.printStackTrace();
           return;
       }
       String received = new String(packet.getData());
       if (DEBUG) {
           System.out.println("Quote of the Moment: " + received);
       }
       display.setText(received);
   }
   public void actionPerformed(ActionEvent event) {
       int port;
       
       try {
           port = Integer.parseInt(portField.getText());
           doIt(port);
       } catch (NumberFormatException e) {
           //No integer entered.  Should warn the user.
       }
   }

}

//File: quoteApplet.html <HTML> <TITLE> QuoteClientApplet </TITLE> <BODY> <APPLET CODE=QuoteClientApplet.class WIDTH=500 HEIGHT=100> </APPLET> </BODY> </HTML>


 </source>
   
  
 
  



Applet Sound

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/* <html> <body>

   <applet code=SoundExample.class width=450 height=50>
   </applet>

</body> </html>

  • /

/*

* 1.1 version.
*/

import java.applet.Applet; import java.applet.AudioClip; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; public class SoundExample extends Applet implements ActionListener {

 SoundList soundList;
 String onceFile = "bark.au";
 String loopFile = "train.au";
 AudioClip onceClip;
 AudioClip loopClip;
 Button playOnce;
 Button startLoop;
 Button stopLoop;
 Button reload;
 boolean looping = false;
 public void init() {
   playOnce = new Button("Bark!");
   playOnce.addActionListener(this);
   add(playOnce);
   startLoop = new Button("Start sound loop");
   stopLoop = new Button("Stop sound loop");
   stopLoop.setEnabled(false);
   startLoop.addActionListener(this);
   add(startLoop);
   stopLoop.addActionListener(this);
   add(stopLoop);
   reload = new Button("Reload sounds");
   reload.addActionListener(this);
   add(reload);
   startLoadingSounds();
 }
 void startLoadingSounds() {
   //Start asynchronous sound loading.
   soundList = new SoundList(this, getCodeBase());
   soundList.startLoading(loopFile);
   soundList.startLoading(onceFile);
 }
 public void stop() {
   onceClip.stop(); //Cut short the one-time sound.
   if (looping) {
     loopClip.stop(); //Stop the sound loop.
   }
 }
 public void start() {
   if (looping) {
     loopClip.loop(); //Restart the sound loop.
   }
 }
 public void actionPerformed(ActionEvent event) {
   //PLAY BUTTON
   Object source = event.getSource();
   if (source == playOnce) {
     if (onceClip == null) {
       //Try to get the AudioClip.
       onceClip = soundList.getClip(onceFile);
     }
     if (onceClip != null) { //If the sound is loaded:
       onceClip.play(); //Play it once.
       showStatus("Playing sound " + onceFile + ".");
     } else {
       showStatus("Sound " + onceFile + " not loaded yet.");
     }
     return;
   }
   //START LOOP BUTTON
   if (source == startLoop) {
     if (loopClip == null) {
       //Try to get the AudioClip.
       loopClip = soundList.getClip(loopFile);
     }
     if (loopClip != null) { //If the sound is loaded:
       looping = true;
       loopClip.loop(); //Start the sound loop.
       stopLoop.setEnabled(true); //Enable stop button.
       startLoop.setEnabled(false); //Disable start button.
       showStatus("Playing sound " + loopFile + " continuously.");
     } else {
       showStatus("Sound " + loopFile + " not loaded yet.");
     }
     return;
   }
   //STOP LOOP BUTTON
   if (source == stopLoop) {
     if (looping) {
       looping = false;
       loopClip.stop(); //Stop the sound loop.
       startLoop.setEnabled(true); //Enable start button.
       stopLoop.setEnabled(false); //Disable stop button.
     }
     showStatus("Stopped playing sound " + loopFile + ".");
     return;
   }
   //RELOAD BUTTON
   if (source == reload) {
     if (looping) { //Stop the sound loop.
       looping = false;
       loopClip.stop();
       startLoop.setEnabled(true); //Enable start button.
       stopLoop.setEnabled(false); //Disable stop button.
     }
     loopClip = null; //Reset AudioClip to null.
     onceClip = null; //Reset AudioClip to null.
     startLoadingSounds();
     showStatus("Reloading all sounds.");
     return;
   }
 }

} /*

* Code is the same in both 1.0 and 1.1.
*/

//Loads and holds a bunch of audio files whose locations are specified //relative to a fixed base URL. class SoundList extends java.util.Hashtable {

 Applet applet;
 URL baseURL;
 public SoundList(Applet applet, URL baseURL) {
   super(5); //Initialize Hashtable with capacity of 5 entries.
   this.applet = applet;
   this.baseURL = baseURL;
 }
 public void startLoading(String relativeURL) {
   new SoundLoader(applet, this, baseURL, relativeURL);
 }
 public AudioClip getClip(String relativeURL) {
   return (AudioClip) get(relativeURL);
 }
 public void putClip(AudioClip clip, String relativeURL) {
   put(relativeURL, clip);
 }

} /*

* Code is the same in both 1.0 and 1.1.
*/

class SoundLoader extends Thread {

 Applet applet;
 SoundList soundList;
 URL baseURL;
 String relativeURL;
 public SoundLoader(Applet applet, SoundList soundList, URL baseURL,
     String relativeURL) {
   this.applet = applet;
   this.soundList = soundList;
   this.baseURL = baseURL;
   this.relativeURL = relativeURL;
   setPriority(MIN_PRIORITY);
   start();
 }
 public void run() {
   AudioClip audioClip = applet.getAudioClip(baseURL, relativeURL);
   //AudioClips load too fast for me!
   //Simulate slow loading by adding a delay of up to 10 seconds.
   try {
     sleep((int) (Math.random() * 10000));
   } catch (InterruptedException e) {
   }
   soundList.putClip(audioClip, relativeURL);
 }

}


 </source>
   
  
 
  



Applet System Properties

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/**

* This applet is the same in 1.1 as in 1.0.
* 
* @author Marianne Mueller
* @author Kathy Walrath
*/

import java.applet.Applet; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Label; public class GetOpenProperties extends Applet implements Runnable {

 String[] propertyNames = { "file.separator", "line.separator",
     "path.separator", "java.class.version", "java.vendor",
     "java.vendor.url", "java.version", "os.name", "os.arch",
     "os.version" };
 final int numProperties = propertyNames.length;
 Label[] values;
 public void init() {
   //Set up the layout.
   GridBagLayout gridbag = new GridBagLayout();
   setLayout(gridbag);
   GridBagConstraints labelConstraints = new GridBagConstraints();
   GridBagConstraints valueConstraints = new GridBagConstraints();
   labelConstraints.anchor = GridBagConstraints.WEST;
   labelConstraints.ipadx = 10;
   valueConstraints.fill = GridBagConstraints.HORIZONTAL;
   valueConstraints.gridwidth = GridBagConstraints.REMAINDER;
   valueConstraints.weightx = 1.0; //Extra space to values column.
   //Set up the Label arrays.
   Label[] names = new Label[numProperties];
   values = new Label[numProperties];
   String firstValue = "not read yet";
   for (int i = 0; i < numProperties; i++) {
     names[i] = new Label(propertyNames[i]);
     gridbag.setConstraints(names[i], labelConstraints);
     add(names[i]);
     values[i] = new Label(firstValue);
     gridbag.setConstraints(values[i], valueConstraints);
     add(values[i]);
   }
   new Thread(this, "Loading System Properties").start();
 }
 /*
  * This method runs in a separate thread, loading properties one by one.
  */
 public void run() {
   String value = null;
   Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
   //Pause to let the reader see the default strings.
   pause(3000);
   for (int i = 0; i < numProperties; i++) {
     //Pause for dramatic effect.
     pause(250);
     try {
       value = System.getProperty(propertyNames[i]);
       values[i].setText(value);
     } catch (SecurityException e) {
       values[i].setText("Could not read: " + "SECURITY EXCEPTION!");
     }
   }
 }
 synchronized void pause(int millis) {
   try {
     wait(millis);
   } catch (InterruptedException e) {
   }
 }

}


 </source>
   
  
 
  



AppletViewer - a simple Applet Viewer program

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.applet.Applet; import java.applet.AppletContext; import java.applet.AppletStub; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.Label; import java.awt.Panel; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.JFrame; /*

* AppletViewer - a simple Applet Viewer program.
* @author  Ian Darwin, http://www.darwinsys.ru/
*/

public class AppletViewer {

 /** The main Frame of this program */
 JFrame f;
 /** The AppletAdapter (gives AppletStub, AppletContext, showStatus) */
 static AppletAdapter aa = null;
 /** The name of the Applet subclass */
 String appName = null;
 /** The Class for the actual applet type */
 Class ac = null;
 /** The Applet instance we are running, or null. Can not be a JApplet
  * until all the entire world is converted to JApplet. */
 Applet ai = null;
 /** The width of the Applet */
 final int WIDTH = 250;
 /** The height of the Applet */
 final int HEIGHT = 200;
 /** Main is where it all starts. 
  * Construct the GUI. Load the Applet. Start it running.
  */
 public static void main(String[] av) {
   new AppletViewer(av.length==0?"HelloApplet":av[0]);
 }
 /** Construct the GUI for an Applet Viewer */
 AppletViewer(String appName) {
   super();
   this.appName = appName;
   f = new JFrame("AppletViewer");
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       f.setVisible(false);
       f.dispose();
       System.exit(0);
     }
   });
   Container cp = f.getContentPane();
   cp.setLayout(new BorderLayout());
   // Instantiate the AppletAdapter which gives us
   // AppletStub and AppletContext.
   if (aa == null)
     aa = new AppletAdapter();
   // The AppletAdapter also gives us showStatus.
   // Therefore, must add() it very early on, since the Applet"s
   // Constructor or its init() may use showStatus()
   cp.add(BorderLayout.SOUTH, aa);
   showStatus("Loading Applet " + appName);
   loadApplet(appName , WIDTH, HEIGHT);  // sets ac and ai
   if (ai == null)
     return;
   // Now right away, tell the Applet how to find showStatus et al.
   ai.setStub(aa);
   // Connect the Applet to the Frame.
   cp.add(BorderLayout.CENTER, ai);
   Dimension d = ai.getSize();
   d.height += aa.getSize().height;
   f.setSize(d);
   f.setVisible(true);    // make the Frame and all in it appear
   showStatus("Applet " + appName + " loaded");
   // Here we pretend to be a browser!
   ai.init();
   ai.start();
 }
 /*
  * Load the Applet into memory. Should do caching.
  */
 void loadApplet(String appletName, int w, int h) {
   // appletName = ... extract from the HTML CODE= somehow ...;
   // width =     ditto
   // height =     ditto
   try {
     // get a Class object for the Applet subclass
     ac = Class.forName(appletName);
     // Construct an instance (as if using no-argument constructor)
     ai = (Applet) ac.newInstance();
   } catch(ClassNotFoundException e) {
     showStatus("Applet subclass " + appletName + " did not load");
     return;
   } catch (Exception e ){
     showStatus("Applet " + appletName + " did not instantiate");
     return;
   }
   ai.setSize(w, h);
 }
 public void showStatus(String s) {
   aa.getAppletContext().showStatus(s);
 }

} /*

* AppletAdaptor: partial implementation of AppletStub and AppletContext.
*
* This code is far from finished, as you will see.
*
* @author  Ian Darwin, http://www.darwinsys.ru/, for Learning Tree Course 478
*/

class AppletAdapter extends Panel implements AppletStub, AppletContext {

 /** The status window at the bottom */
 Label status = null;
 /** Construct the GUI for an Applet Status window */
 AppletAdapter() {
   super();
   // Must do this very early on, since the Applet"s
   // Constructor or its init() may use showStatus()
   add(status = new Label());
   // Give "status" the full width
   status.setSize(getSize().width, status.getSize().height);
   showStatus("AppletAdapter constructed");  // now it can be said
 }
 /****************** AppletStub ***********************/
 /** Called when the applet wants to be resized.  */
 public void appletResize(int w, int h) {
   // applet.setSize(w, h);
 }
 /** Gets a reference to the applet"s context.  */
 public AppletContext getAppletContext() {
   return this;
 }
 /** Gets the base URL.  */
 public URL getCodeBase() {
   return getClass().getResource(".");
 }
 /** Gets the document URL.  */
 public URL getDocumentBase() {
   return getClass().getResource(".");
 }
 /** Returns the value of the named parameter in the HTML tag.  */
 public String getParameter(String name) {
   String value = null;
   return value;
 }
 /** Determines if the applet is active.  */
 public boolean isActive() {
   return true;
 }
 /************************ AppletContext ************************/
 /** Finds and returns the applet with the given name. */
 public Applet getApplet(String an) {
   return null;
 }
 /** Finds all the applets in the document */
 public Enumeration getApplets()  {
   class AppletLister implements Enumeration {
     public boolean hasMoreElements() {
       return false;
     }
     public Object nextElement() {
       return null;
     }
   }
   return new AppletLister();
 }
 /** Create an audio clip for the given URL of a .au file */
 public AudioClip getAudioClip(URL u) {
   return null;
 }
 /** Look up and create an Image object that can be paint()ed */
 public Image getImage(URL u)  {
   return null;
 }
 /** Request to overlay the current page with a new one - ignored */
 public void showDocument(URL u) {
 }
 /** as above but with a Frame target */
 public void showDocument(URL u, String frame)  {
 }
 /** Called by the Applet to display a message in the bottom line */
 public void showStatus(String msg) {
   if (msg == null)
     msg = "";
   status.setText(msg);
 }
 /* StreamKey stuff - new in JDK1.4 */
 Map streamMap = new HashMap();
 /** Associate the stream with the key. */
 public void setStream(String key, InputStream stream) throws IOException {
   streamMap.put(key, stream);
 }
 public InputStream getStream(String key) {
   return (InputStream)streamMap.get(key);
 }
 public Iterator getStreamKeys() {
   return streamMap.keySet().iterator();
 }

}



 </source>
   
  
 
  



Applet with parameters

   <source lang="java">
 

//File: applet.html /* <applet code="ColorScribble.class"

 codebase="."
 width=400 height=400>
 <param name="foreground" value="FF0000">
 <param name="background" value="CCFFCC">

</applet>

  • /

/*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; /**

* A version of the Scribble applet that reads two applet parameters to set the
* foreground and background colors. It also returns information about itself
* when queried.
*/

public class ColorScribble extends Applet{

 // Read in two color parameters and set the colors.
 public void init() {
   Color foreground = getColorParameter("foreground");
   Color background = getColorParameter("background");
   if (foreground != null)
     this.setForeground(foreground);
   if (background != null)
     this.setBackground(background);
 }
 public void paint(Graphics g) {
   g.setColor(getForeground());
   g.drawString("Parameter",10, 10 );
 }
 // Read the specified parameter. Interpret it as a hexadecimal
 // number of the form RRGGBB and convert it to a color.
 protected Color getColorParameter(String name) {
   String value = this.getParameter(name);
   try {
     return new Color(Integer.parseInt(value, 16));
   } catch (Exception e) {
     return null;
   }
 }
 // Return information suitable for display in an About dialog box.
 public String getAppletInfo() {
   return "ColorScribble v. 0.03.  Written by David Flanagan.";
 }
 // Return info about the supported parameters. Web browsers and applet
 // viewers should display this information, and may also allow users to
 // set the parameter values.
 public String[][] getParameterInfo() {
   return info;
 }
 // Here"s the information that getParameterInfo() returns.
 // It is an array of arrays of strings describing each parameter.
 // Format: parameter name, parameter type, parameter description
 private String[][] info = {
     { "foreground", "hexadecimal color value", "foreground color" },
     { "background", "hexadecimal color value", "background color" } };

}



 </source>
   
  
 
  



A simple loan calculator applet

   <source lang="java">
 

/*

* Chapter 9 - Financial Applets and Servlets The Art of Java by Herbert Schildt
* and James Holmes McGraw-Hill/Osborne 2003
*  
*/

import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; /*

* <applet code="RegPay" width=280 height=200> </applet>
*/

public class RegPay extends Applet implements ActionListener {

 TextField amountText, paymentText, periodText, rateText;
 Button doIt;
 double principal; // original princial
 double intRate; // interest rate
 double numYears; // length of loan in years
 /*
  * Number of payments per year. You could allow this value to be set by the
  * user.
  */
 final int payPerYear = 12;
 NumberFormat nf;
 public void init() {
   // Use a grid bag layout.
   GridBagLayout gbag = new GridBagLayout();
   GridBagConstraints gbc = new GridBagConstraints();
   setLayout(gbag);
   Label heading = new Label("Compute Monthly Loan Payments");
   Label amountLab = new Label("Principal");
   Label periodLab = new Label("Years");
   Label rateLab = new Label("Interest Rate");
   Label paymentLab = new Label("Monthly Payments");
   amountText = new TextField(16);
   periodText = new TextField(16);
   paymentText = new TextField(16);
   rateText = new TextField(16);
   // Payment field for display only.
   paymentText.setEditable(false);
   doIt = new Button("Compute");
   // Define the grid bag.
   gbc.weighty = 1.0; // use a row weight of 1
   gbc.gridwidth = GridBagConstraints.REMAINDER;
   gbc.anchor = GridBagConstraints.NORTH;
   gbag.setConstraints(heading, gbc);
   // Anchor most components to the right.
   gbc.anchor = GridBagConstraints.EAST;
   gbc.gridwidth = GridBagConstraints.RELATIVE;
   gbag.setConstraints(amountLab, gbc);
   gbc.gridwidth = GridBagConstraints.REMAINDER;
   gbag.setConstraints(amountText, gbc);
   gbc.gridwidth = GridBagConstraints.RELATIVE;
   gbag.setConstraints(periodLab, gbc);
   gbc.gridwidth = GridBagConstraints.REMAINDER;
   gbag.setConstraints(periodText, gbc);
   gbc.gridwidth = GridBagConstraints.RELATIVE;
   gbag.setConstraints(rateLab, gbc);
   gbc.gridwidth = GridBagConstraints.REMAINDER;
   gbag.setConstraints(rateText, gbc);
   gbc.gridwidth = GridBagConstraints.RELATIVE;
   gbag.setConstraints(paymentLab, gbc);
   gbc.gridwidth = GridBagConstraints.REMAINDER;
   gbag.setConstraints(paymentText, gbc);
   gbc.anchor = GridBagConstraints.CENTER;
   gbag.setConstraints(doIt, gbc);
   // Add all the components.
   add(heading);
   add(amountLab);
   add(amountText);
   add(periodLab);
   add(periodText);
   add(rateLab);
   add(rateText);
   add(paymentLab);
   add(paymentText);
   add(doIt);
   // Register to receive action events.
   amountText.addActionListener(this);
   periodText.addActionListener(this);
   rateText.addActionListener(this);
   doIt.addActionListener(this);
   nf = NumberFormat.getInstance();
   nf.setMinimumFractionDigits(2);
   nf.setMaximumFractionDigits(2);
 }
 /*
  * User pressed Enter on a text field or pressed Compute.
  */
 public void actionPerformed(ActionEvent ae) {
   repaint();
 }
 // Display the result if all fields are completed.
 public void paint(Graphics g) {
   double result = 0.0;
   String amountStr = amountText.getText();
   String periodStr = periodText.getText();
   String rateStr = rateText.getText();
   try {
     if (amountStr.length() != 0 && periodStr.length() != 0
         && rateStr.length() != 0) {
       principal = Double.parseDouble(amountStr);
       numYears = Double.parseDouble(periodStr);
       intRate = Double.parseDouble(rateStr) / 100;
       result = compute();
       paymentText.setText(nf.format(result));
     }
     showStatus(""); // erase any previous error message
   } catch (NumberFormatException exc) {
     showStatus("Invalid Data");
     paymentText.setText("");
   }
 }
 // Compute the loan payment.
 double compute() {
   double numer;
   double denom;
   double b, e;
   numer = intRate * principal / payPerYear;
   e = -(payPerYear * numYears);
   b = (intRate / payPerYear) + 1.0;
   denom = 1.0 - Math.pow(b, e);
   return numer / denom;
 }

}



 </source>
   
  
 
  



Bookmarks

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <html> <head>

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>We"ve moved!</title>

</head> <body bgcolor="White">

We"ve moved!

<p>Please update your bookmarks. Our new address is:

<applet code=Redir.class width=300 heighT=100 alt="http://www.jexp.ru">

 <param name="URL" value="http://www.jexp.ru">
 http://www.jexp.ru

</applet>


If you have a Java-enabled browser, we"ll try to take you there in a few seconds.

</body> </html>

  • /

import java.applet.Applet; import java.awt.Graphics; import java.net.URL; /**

* A simple redirection applet.
* 
* @author Ian Darwin
*/

public class Redir extends Applet implements Runnable {

 protected String urlString;
 protected URL theNewURL;
 protected final static int NSECONDS = 5;
 protected Thread t;
 public void init() {
   try {
     // Get the address from a PARAM...
     urlString = getParameter("URL");
     if (urlString == null) {
       urlString = "MISSING URL";
       throw new IllegalArgumentException(
           "Redir requires a URL parameter in the HTML");
     }
     // Make up the URL object
     theNewURL = new URL(urlString);
     // debug...
     // showStatus("URL = " + theNewURL);
   } catch (Exception err) {
     System.err.println("Error!\n" + err);
     showStatus("Error, look in Java Console for details!");
   }
 }
 public void start() {
   if (theNewURL == null)
     return;
   t = new Thread(this);
   t.start();
 }
 /** Print a little message to the user. */
 public void paint(Graphics g) {
   if (urlString != null)
     g.drawString(urlString, 20, 50);
   else
     g.drawString("Initializing...", 20, 50);
 }
 /**
  * If users moves off the page, set Thread t to null so we don"t
  * showDocument from within the middle of the new page!
  */
 public void stop() {
   t = null;
 }
 /**
  * run, called by the Thread, does the work of sleeping for a fixed number
  * of seconds then, if the user hasn"t moved off the page, actually passing
  * control to the new page.
  */
 public void run() {
   for (int i = NSECONDS; i >= 0; i--) {
     try {
       Thread.sleep(1000);
       if (t == null)
         return;
     } catch (InterruptedException e) {
       // so what?
     }
     if (t == null)
       return;
     showStatus(Integer.toString(i));
     if (t == null)
       return;
     showStatus("Ignition!");
     // "And then a miracle occurs..."
     getAppletContext().showDocument(theNewURL);
   }
 }

}



 </source>
   
  
 
  



Bouncing Circle

   <source lang="java">
 

/*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; /** An applet that displays a simple animation */ public class BouncingCircle extends Applet implements Runnable {

 int x = 150, y = 50, r = 50; // Position and radius of the circle
 int dx = 11, dy = 7; // Trajectory of circle
 Thread animator; // The thread that performs the animation
 volatile boolean pleaseStop; // A flag to ask the thread to stop
 /** This method simply draws the circle at its current position */
 public void paint(Graphics g) {
   g.setColor(Color.red);
   g.fillOval(x - r, y - r, r * 2, r * 2);
 }
 /**
  * This method moves (and bounces) the circle and then requests a redraw.
  * The animator thread calls this method periodically.
  */
 public void animate() {
   // Bounce if we"ve hit an edge.
   Rectangle bounds = getBounds();
   if ((x - r + dx < 0) || (x + r + dx > bounds.width))
     dx = -dx;
   if ((y - r + dy < 0) || (y + r + dy > bounds.height))
     dy = -dy;
   // Move the circle.
   x += dx;
   y += dy;
   // Ask the browser to call our paint() method to draw the circle
   // at its new position.
   repaint();
 }
 /**
  * This method is from the Runnable interface. It is the body of the thread
  * that performs the animation. The thread itself is created and started in
  * the start() method.
  */
 public void run() {
   while (!pleaseStop) { // Loop until we"re asked to stop
     animate(); // Update and request redraw
     try {
       Thread.sleep(100);
     } // Wait 100 milliseconds
     catch (InterruptedException e) {
     } // Ignore interruptions
   }
 }
 /** Start animating when the browser starts the applet */
 public void start() {
   animator = new Thread(this); // Create a thread
   pleaseStop = false; // Don"t ask it to stop now
   animator.start(); // Start the thread.
   // The thread that called start now returns to its caller.
   // Meanwhile, the new animator thread has called the run() method
 }
 /** Stop animating when the browser stops the applet */
 public void stop() {
   // Set the flag that causes the run() method to end
   pleaseStop = true;
 }

}


 </source>
   
  
 
  



Calling methods of an Applet from JavaScript code

   <source lang="java">
 

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Label; public class Main extends Applet {

 private Label  m_mess = new Label("asdf", Label.CENTER);
 public void init() {
   add(BorderLayout.CENTER, m_mess);
 }
 public void setMessage(String message) {
   m_mess.setText("Selection : " + message);
 }

}

<html> <HEAD> <TITLE> JavaScript to Applet Communication </TITLE > <SCRIPT LANGUAGE="JavaScript"> function selectedCity() {

   document.SimpleMessageApplet.setMessage("hi");

} </SCRIPT> </HEAD> <BODY > This is the Applet

<APPLET CODE="MessageApplet.class" NAME="SimpleMessageApplet" WIDTH=350 HEIGHT=100 > </APPLET > </BODY > </html>


 </source>
   
  
 
  



Change an applet background color

   <source lang="java">
 

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Main extends Applet {

 public void init() {
   setBackground(Color.WHITE);
 }
 public void paint(Graphics g) {
   g.setColor(Color.BLACK);
   g.drawString("Applet background example", 0, 50);
 }

}


 </source>
   
  
 
  



Demo Applet: Connect to Legacy System

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <HTML> <HEAD> <TITLE>Demo Applet: Connect to Legacy System</TITLE> </HEAD> <BODY BGCOLOR="96FF6F">

Demo Applet: Connect to Legacy Server

Please use this applet to Login to our server server. This will demonstrate an Applet via a Socket connection.

Thank you!


<APPLET CODE="SocketApplet" width=300 height=120> </APPLET>


<Address>Ian@DarwinSys.ru</ADDRESS> </BODY> </HTML>

  • /

import java.applet.Applet; import java.awt.Button; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.URL; /**

* Socket Applet for "legacy" server connection via Socket.
* 
* @version $Id: SocketApplet.java,v 1.5 2004/02/09 03:33:44 ian Exp $
* @author Ian F. Darwin, http://www.darwinsys.ru/
*/

public class SocketApplet extends Applet {

 TextField nameTF, passTF, domainTF;
 Image im;
 Button sendButton;
 /** Where the Applet came from */
 URL whence;
 //+
 /** Initialize the GUI nicely. */
 public void init() {
   Label aLabel;
   setLayout(new GridBagLayout());
   int LOGO_COL = 1;
   int LABEL_COL = 2;
   int TEXT_COL = 3;
   int BUTTON_COL = 1;
   GridBagConstraints gbc = new GridBagConstraints();
   gbc.weightx = 100.0;
   gbc.weighty = 100.0;
   gbc.gridx = LABEL_COL;
   gbc.gridy = 0;
   gbc.anchor = GridBagConstraints.EAST;
   add(aLabel = new Label("Name:", Label.CENTER), gbc);
   gbc.anchor = GridBagConstraints.CENTER;
   gbc.gridx = TEXT_COL;
   gbc.gridy = 0;
   add(nameTF = new TextField(10), gbc);
   gbc.gridx = LABEL_COL;
   gbc.gridy = 1;
   gbc.anchor = GridBagConstraints.EAST;
   add(aLabel = new Label("Password:", Label.CENTER), gbc);
   gbc.anchor = GridBagConstraints.CENTER;
   gbc.gridx = TEXT_COL;
   gbc.gridy = 1;
   add(passTF = new TextField(10), gbc);
   passTF.setEchoChar("*");
   gbc.gridx = LABEL_COL;
   gbc.gridy = 2;
   gbc.anchor = GridBagConstraints.EAST;
   add(aLabel = new Label("Domain:", Label.CENTER), gbc);
   gbc.anchor = GridBagConstraints.CENTER;
   gbc.gridx = TEXT_COL;
   gbc.gridy = 2;
   add(domainTF = new TextField(10), gbc);
   sendButton = new Button("Send data");
   gbc.gridx = BUTTON_COL;
   gbc.gridy = 3;
   gbc.gridwidth = 3;
   add(sendButton, gbc);
   whence = getCodeBase();
   // Now the action begins...
   sendButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       String name = nameTF.getText();
       if (name.length() == 0) {
         showStatus("Name required");
         return;
       }
       String domain = domainTF.getText();
       if (domain.length() == 0) {
         showStatus("Domain required");
         return;
       }
       showStatus("Connecting to host " + whence.getHost() + " as "
           + nameTF.getText());
       try {
         Socket s = new Socket(getCodeBase().getHost(),3333);
         PrintWriter pf = new PrintWriter(s.getOutputStream(), true);
         // send login name
         pf.println(nameTF.getText());
         // passwd
         pf.println(passTF.getText());
         // and domain
         pf.println(domainTF.getText());
         BufferedReader is = new BufferedReader(
             new InputStreamReader(s.getInputStream()));
         String response = is.readLine();
         showStatus(response);
       } catch (IOException e) {
         showStatus("ERROR: " + e.getMessage());
       }
     }
   });
 }
 //-

}



 </source>
   
  
 
  



Demo Choice Applet

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//// //applet.html /* <TITLE>Ian Darwin"s Demo Choice Applet</TITLE> <BODY BGCOLOR="#c0e0d0">

Ian Darwin"s Demo Choice Applet

Here it is, just what you need to replace JavaScript with:

<APPLET CODE=SumUp WIDTH=250 HEIGHT=150> </APPLET> </TABLE>


<P>Hey, we"ll even show you .

  • /

import java.applet.Applet; import java.awt.Button; import java.awt.Choice; import java.awt.Color; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; /**

* <p>
* SumUp is a simple applet that adds up some numbers. To make this really
* useful for production, should implement a "little language" either in HTML
* PARAMs, such as
* 
*
 * 
 *   &ltparam name="title1" value="Option One">
 *   &ltparam name="values1" value="0|100|200|300|400">
 *   &ltparam name="title1" value="Option Two">
 *   &ltparam name="values1" value="0|400|600|800|1000">
 *  
 * 
* 
* 
or
in a configuration file which we download and parse (see * TreeLink.java in this directory) or load as a Properties file (see * MenuIntl.java).
*

*

* Also, of course, the URL to go to should be a PARAM. Not to mention the * colors (see ColorName and/or XColor). *

* 
* @author Ian F. Darwin, http://www.darwinsys.ru/
*/

public class SumUp extends Applet implements ActionListener {

 /** The array of Choice items */
 protected Choice cs[] = new Choice[10];
 /** How many are actually in the array. */
 protected int numChoices = 0;
 /** The result of the summation */
 protected Label resultField;
 /** The pushbutton to send the form in */
 protected Button sendButton;
 /** init() is an Applet method called by the browser to initialize */
 public void init() {
   setBackground(Color.magenta);
   // The layout of the Applet is a Grid; always add things in pairs!
   setLayout(new GridLayout(0, 2));
   Choice c;
   add(new Label("Option 1"));
   add(c = new Choice());
   c.addItem("0");
   c.addItem("100");
   c.addItem("200");
   c.addItem("400");
   cs[numChoices++] = c;
   add(new Label("Option 2"));
   add(c = new Choice());
   c.addItem("0");
   c.addItem("100");
   c.addItem("200");
   c.addItem("400");
   cs[numChoices++] = c;
   Panel p = new Panel();
   p.setBackground(Color.pink);
   p.add(new Label("Total:"));
   p.add(resultField = new Label("000000"));
   add(p);
   sendButton = new Button("Send it");
   add(sendButton); // connect Button into Applet
   sendButton.addActionListener(this); // connect it back to Applet
 }
 /**
  * actionPerforformed() is called when a "high level" action happens (like
  * the user pushing a Button!) in one of the components added to this
  * Applet.
  */
 public void actionPerformed(ActionEvent e) { // 1.1
   int total = 0;
   for (int i = 0; i < numChoices; i++) {
     String text = cs[i].getSelectedItem();
     // System.err.println("Selection " + i + " = " + text);
     int value = Integer.parseInt(text);
     total += value;
   }
   resultField.setText(Integer.toString(total));
   try {
     URL myNewURL = new URL("http://server/cgi-bin/credit?sum=" + total);
     // System.out.println("URL = " + myNewURL); // debug...
     // "And then a miracle occurs..."
     getAppletContext().showDocument(myNewURL);
   } catch (Exception err) {
     System.err.println("Error!\n" + err);
     showStatus("Error, look in Java Console for details!");
   }
 }

}


 </source>
   
  
 
  



Demonstrates getParameterInfo() and getAppletInfo()

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <html><title>ParmInfoDemo</title></head> <body bgcolor="White">

ParmInfoDemo

<applet code="ParmInfoDemo.class" width=300 height=60>

 <param name="fontsize" value="24">

You need Java to view this!

</applet>

  • /

import java.applet.Applet; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Label; /** Null Demo, just demonstrates getParameterInfo() and getAppletInfo() */ public class ParmInfoDemo extends Applet {

 /** Init routine: set a font, initialize UI components. */
 public void init() {
   setLayout(new FlowLayout());
   String psize = getParameter("fontsize");
   if (psize == null)
     psize = "12";
   System.out.println("Fontsize is " + psize);
   Font f = new Font("Helvetica", Font.PLAIN, Integer.parseInt(psize));
   Label l = new Label("Font Demo");
   l.setFont(f);
   add(l);
 }
 /** Return information about this applet. */
 public String getAppletInfo() {
   return "ParmInfoDemo Applet, Version 0\n"
       + "Copyright Learning Tree International";
 }
 /** Return list of allowable parameters. */
 public String[][] getParameterInfo() {
   String param_info[][] = { { "fontsize", "10-20", "Size of font" }, };
   return param_info;
 }

}



 </source>
   
  
 
  



Demonstration of Applet Methods

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <title>Demonstration of Applet Methods</title> <body bgcolor="white">

Demonstration of Applet Methods

<applet code="AppletMethods" width=200 height=100>

 <param name="SNDFILE" VALUE="foo.au">

</applet>

  • /

import java.applet.Applet; import java.applet.AudioClip; import java.awt.Graphics; import java.net.MalformedURLException; import java.net.URL; /** AppletMethods -- show stop/start and AudioClip methods */ public class AppletMethods extends Applet {

 /** AudioClip object, used to load and play a sound file. */
 AudioClip snd = null;
 /** Initialize the sound file object and the GUI. */
 public void init() {
   System.out.println("In AppletMethods.init()");
   try {
     snd = getAudioClip(new URL(getCodeBase(), "laugh.au"));
   } catch (MalformedURLException e) {
     showStatus(e.toString());
   }
   setSize(200,100);  // take the place of a GUI
 }
 /** Called from the Browser when the page is ready to go. */
 public void start() {
   System.out.println("In AppletMethods.start()");
   if (snd != null)
     snd.play();  // loop() to be obnoxious...
 }
 /** Called from the Browser when the page is being vacated. */
 public void stop() {
   System.out.println("In AppletMethods.stop()");
   if (snd != null)
     snd.stop();  // stop play() or loop() 
 }
 /** Called from the Browser (when the applet is being un-cached?).
  * Not actually used here, but the println will show when it"s called.
  */
 public void destroy() {
   System.out.println("In AppletMethods.destroy()");
 }
 public void paint(Graphics g) {
   g.drawString("Welcome to Java", 50, 50);
 }
 /** An alternate form of getParameter that lets
  * you provide a default value, since this is so common.
  */
 public String getParameter(String p, String def) {
   return getParameter(p)==null?def:getParameter(p);
 }

}



 </source>
   
  
 
  



Display message in browser status bar

   <source lang="java">
 

import java.applet.Applet; public class Main extends Applet {

 public void init() {
   this.showStatus("asdf");
 }
 public void start() {
   
 }
 public void stop() {
 }

}


 </source>
   
  
 
  



First applet

   <source lang="java">
 

//File: applet.html /* <applet code="FirstApplet.class"

 codebase="."
 width=150 height=100>

</applet>

  • /

/// import java.applet.Applet; import java.awt.Graphics; /** This applet just says "Hello World! */ public class FirstApplet extends Applet {

 // This method displays the applet.
 public void paint(Graphics g) {
   g.drawString("Hello World", 25, 50);
 }

}



 </source>
   
  
 
  



Get Applets

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Button; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; public class GetApplets extends Applet implements ActionListener {

 private TextArea textArea;
 private String newline;
 public void init() {
   Button b = new Button("Click to call getApplets()");
   b.addActionListener(this);
   setLayout(new BorderLayout());
   add("North", b);
   textArea = new TextArea(5, 40);
   textArea.setEditable(false);
   add("Center", textArea);
   newline = System.getProperty("line.separator");
 }
 public void actionPerformed(ActionEvent event) {
   printApplets();
 }
 public String getAppletInfo() {
   return "GetApplets by Kathy Walrath";
 }
 public void printApplets() {
   //Enumeration will contain all applets on this page
   //(including this one) that we can send messages to.
   Enumeration e = getAppletContext().getApplets();
   textArea.append("Results of getApplets():" + newline);
   while (e.hasMoreElements()) {
     Applet applet = (Applet) e.nextElement();
     String info = ((Applet) applet).getAppletInfo();
     if (info != null) {
       textArea.append("- " + info + newline);
     } else {
       textArea.append("- " + applet.getClass().getName() + newline);
     }
   }
   textArea.append("________________________" + newline + newline);
 }

}


 </source>
   
  
 
  



Get list of APPLET tags in one HTML file

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.Vector; /**

* Get list of APPLET tags in one HTML file.
* 
* @author Ian Darwin, Darwin Open Systems, www.darwinsys.ru. Routine "readTag"
*         shamelessly stolen from Elliott Rusty Harold"s "ImageSizer" program.
*/

public class AppletFinder {

 public static void main(String[] av) {
   String[] tags = new AppletFinder().doPage(av[0]);
   for (int i = 0; i < tags.length; i++)
     System.out.println("APPLET: " + i + " " + tags[i]);
 }
 public String[] doPage(String pageURL) {
   String result[] = null;
   URL root;
   if (pageURL != null) {
     //Open the URL for reading
     try {
       if (pageURL.indexOf(":") != -1) {
         root = new URL(pageURL);
       } else {
         root = new URL("http://" + pageURL);
       }
       result = findApplets(root);
     } catch (MalformedURLException e) {
       System.err.println(pageURL + " is not a parseable URL");
       System.err.println(e);
     }
   }
   return result;
 }
 public String[] findApplets(URL u) {
   BufferedReader inrdr = null;
   Vector v = new Vector();
   char thisChar = 0;
   try {
     inrdr = new BufferedReader(new InputStreamReader(u.openStream()));
     int i;
     while ((i = inrdr.read()) != -1) {
       thisChar = (char) i;
       if (thisChar == "<") {
         String tag = readTag(inrdr);
         // System.out.println("TAG: " + tag);
         if (tag.toUpperCase().startsWith("<APPLET"))
           v.addElement(tag);
       }
     }
     inrdr.close();
   } catch (IOException e) {
     System.err.println("Error reading from main URL: " + e);
   }
   String applets[] = new String[v.size()];
   v.copyInto(applets);
   return applets;
 }
 public String readTag(BufferedReader is) {
   StringBuffer theTag = new StringBuffer("<");
   char theChar = "<";
   try {
     while (theChar != ">" && ((theChar = (char) is.read()) != -1)) {
       theTag.append(theChar);
     } // end while
   } // end try
   catch (IOException e) {
     System.err.println(e);
   }
   return theTag.toString();
 }

}


 </source>
   
  
 
  



Icon behavior in Jbuttons

   <source lang="java">
 

// : c14:Faces.java // Icon behavior in Jbuttons. // <applet code=Faces width=400 height=100></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; public class Faces extends JApplet {

 private static Icon[] faces;
 private JButton jb, jb2 = new JButton("Disable");
 private boolean mad = false;
 public void init() {
   faces = new Icon[] {
       new ImageIcon(getClass().getResource("Face0.gif")),
       new ImageIcon(getClass().getResource("Face1.gif")),
       new ImageIcon(getClass().getResource("Face2.gif")),
       new ImageIcon(getClass().getResource("Face3.gif")),
       new ImageIcon(getClass().getResource("Face4.gif")), };
   jb = new JButton("JButton", faces[3]);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (mad) {
         jb.setIcon(faces[3]);
         mad = false;
       } else {
         jb.setIcon(faces[0]);
         mad = true;
       }
       jb.setVerticalAlignment(JButton.TOP);
       jb.setHorizontalAlignment(JButton.LEFT);
     }
   });
   jb.setRolloverEnabled(true);
   jb.setRolloverIcon(faces[1]);
   jb.setPressedIcon(faces[2]);
   jb.setDisabledIcon(faces[4]);
   jb.setToolTipText("Yow!");
   cp.add(jb);
   jb2.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       if (jb.isEnabled()) {
         jb.setEnabled(false);
         jb2.setText("Enable");
       } else {
         jb.setEnabled(true);
         jb2.setText("Disable");
       }
     }
   });
   cp.add(jb2);
 }
 public static void main(String[] args) {
   run(new Faces(), 400, 200);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~



 </source>
   
  
 
  



Icon Demo Applet

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.net.URL; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class IconDemoApplet extends JApplet implements ActionListener {

 Vector pictures;
 JButton previousButton;
 JButton nextButton;
 JLabel photographLabel;
 JLabel captionLabel;
 JLabel numberLabel;
 int current = 0;
 int widthOfWidest = 0;
 int heightOfTallest = 0;
 String imagedir = null;
 public void init() {
   //Parse the applet parameters
   pictures = parseParameters();
   //If the applet tag doesn"t provide an "IMAGE0" parameter,
   //display an error message.
   if (pictures.size() == 0) {
     captionLabel = new JLabel("No images listed in applet tag.");
     captionLabel.setHorizontalAlignment(JLabel.CENTER);
     getContentPane().add(captionLabel);
     return;
   }
   //NOW CREATE THE GUI COMPONENTS
   //A label to identify XX of XX.
   numberLabel = new JLabel("Picture " + (current + 1) + " of "
       + pictures.size());
   numberLabel.setHorizontalAlignment(JLabel.LEFT);
   numberLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5));
   //A label for the caption.
   final Photo first = (Photo) pictures.firstElement();
   captionLabel = new JLabel(first.caption);
   captionLabel.setHorizontalAlignment(JLabel.CENTER);
   captionLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
   //A label for displaying the photographs.
   photographLabel = new JLabel("Loading first image...");
   photographLabel.setHorizontalAlignment(JLabel.CENTER);
   photographLabel.setVerticalAlignment(JLabel.CENTER);
   photographLabel.setVerticalTextPosition(JLabel.CENTER);
   photographLabel.setHorizontalTextPosition(JLabel.CENTER);
   photographLabel.setBorder(BorderFactory.createCompoundBorder(
       BorderFactory.createLoweredBevelBorder(), BorderFactory
           .createEmptyBorder(5, 5, 5, 5)));
   photographLabel.setBorder(BorderFactory.createCompoundBorder(
       BorderFactory.createEmptyBorder(0, 0, 10, 0), photographLabel
           .getBorder()));
   //Set the preferred size for the picture,
   //with room for the borders.
   Insets i = photographLabel.getInsets();
   photographLabel.setPreferredSize(new Dimension(widthOfWidest + i.left
       + i.right, heightOfTallest + i.bottom + i.top));
   //Create the next and previous buttons.
   ImageIcon nextIcon = new ImageIcon(getURL(imagedir + "right.gif"));
   ImageIcon dimmedNextIcon = new ImageIcon(getURL(imagedir
       + "dimmedRight.gif"));
   ImageIcon previousIcon = new ImageIcon(getURL(imagedir + "left.gif"));
   ImageIcon dimmedPreviousIcon = new ImageIcon(getURL(imagedir
       + "dimmedLeft.gif"));
   previousButton = new JButton("Previous Picture", previousIcon);
   previousButton.setDisabledIcon(dimmedPreviousIcon);
   previousButton.setVerticalTextPosition(AbstractButton.CENTER);
   previousButton.setHorizontalTextPosition(AbstractButton.RIGHT);
   previousButton.setMnemonic(KeyEvent.VK_P);
   previousButton.setActionCommand("previous");
   previousButton.addActionListener(this);
   previousButton.setEnabled(false);
   nextButton = new JButton("Next Picture", nextIcon);
   nextButton.setDisabledIcon(dimmedNextIcon);
   nextButton.setVerticalTextPosition(AbstractButton.CENTER);
   nextButton.setHorizontalTextPosition(AbstractButton.LEFT);
   nextButton.setMnemonic(KeyEvent.VK_N);
   nextButton.setActionCommand("next");
   nextButton.addActionListener(this);
   //Lay out the GUI.
   GridBagLayout layout = new GridBagLayout();
   GridBagConstraints c = new GridBagConstraints();
   Container contentPane = getContentPane();
   contentPane.setLayout(layout);
   c.gridwidth = GridBagConstraints.REMAINDER;
   c.fill = GridBagConstraints.HORIZONTAL;
   layout.setConstraints(numberLabel, c);
   contentPane.add(numberLabel);
   layout.setConstraints(captionLabel, c);
   contentPane.add(captionLabel);
   c.gridwidth = GridBagConstraints.REMAINDER;
   c.fill = GridBagConstraints.BOTH;
   layout.setConstraints(photographLabel, c);
   contentPane.add(photographLabel);
   c.gridwidth = GridBagConstraints.RELATIVE;
   c.fill = GridBagConstraints.HORIZONTAL;
   layout.setConstraints(previousButton, c);
   contentPane.add(previousButton);
   c.gridwidth = GridBagConstraints.REMAINDER;
   layout.setConstraints(nextButton, c);
   contentPane.add(nextButton);
   //Start loading the image for the first photograph now.
   //The loadImage method uses a SwingWorker
   //to load the image in a separate thread.
   loadImage(imagedir + first.filename, current);
 }
 //User clicked either the next or the previous button.
 public void actionPerformed(ActionEvent e) {
   //Show loading message.
   photographLabel.setIcon(null);
   photographLabel.setText("Loading image...");
   //Compute index of photograph to view.
   if (e.getActionCommand().equals("next")) {
     current += 1;
     if (!previousButton.isEnabled())
       previousButton.setEnabled(true);
     if (current == pictures.size() - 1)
       nextButton.setEnabled(false);
   } else {
     current -= 1;
     if (!nextButton.isEnabled())
       nextButton.setEnabled(true);
     if (current == 0)
       previousButton.setEnabled(false);
   }
   //Get the photo object.
   Photo pic = (Photo) pictures.elementAt(current);
   //Update the caption and number labels.
   captionLabel.setText(pic.caption);
   numberLabel.setText("Picture " + (current + 1) + " of "
       + pictures.size());
   //Update the photograph.
   ImageIcon icon = pic.getIcon();
   if (icon == null) { //haven"t viewed this photo before
     loadImage(imagedir + pic.filename, current);
   } else {
     updatePhotograph(current, pic);
   }
 }
 //Must be invoked from the event-dispatching thread.
 private void updatePhotograph(int index, Photo pic) {
   ImageIcon icon = pic.getIcon();
   photographLabel.setToolTipText(pic.filename + ": "
       + icon.getIconWidth() + " X " + icon.getIconHeight());
   photographLabel.setIcon(icon);
   photographLabel.setText("");
 }
 //Load an image in a separate thread.
 private void loadImage(final String imagePath, final int index) {
   final SwingWorker worker = new SwingWorker() {
     ImageIcon icon = null;
     public Object construct() {
       icon = new ImageIcon(getURL(imagePath));
       return icon; //return value not used by this program
     }
     //Runs on the event-dispatching thread.
     public void finished() {
       Photo pic = (Photo) pictures.elementAt(index);
       pic.setIcon(icon);
       if (index == current)
         updatePhotograph(index, pic);
     }
   };
   worker.start();
 }
 protected URL getURL(String filename) {
   URL codeBase = this.getCodeBase();
   URL url = null;
   try {
     url = new URL(codeBase, filename);
   } catch (java.net.MalformedURLException e) {
     System.out.println("Couldn"t create image: "
         + "badly specified URL");
     return null;
   }
   return url;
 }
 protected Vector parseParameters() {
   Vector pix = new Vector(10); //start with 10, grows if necessary
   int i = 0; //parameters index must start at 0
   String paramName = "IMAGE" + i;
   String paramValue;
   while ((paramValue = getParameter(paramName)) != null) {
     Photo pic = new Photo(paramValue, getCaption(i), getWidth(i),
         getHeight(i));
     pix.addElement(pic);
     i++;
     paramName = "IMAGE" + i;
   }
   //Get the name of the directory that contains the image files.
   imagedir = getParameter("IMAGEDIR");
   if (imagedir != null)
     imagedir = imagedir + "/";
   return pix;
 }
 protected String getCaption(int i) {
   return getParameter("CAPTION" + i);
 }
 protected int getWidth(int i) {
   int width = 0;
   String widthString = getParameter("WIDTH" + i);
   if (widthString != null) {
     try {
       width = Integer.parseInt(widthString);
     } catch (NumberFormatException e) {
       width = 0;
     }
   } else {
     width = 0;
   }
   if (width > widthOfWidest)
     widthOfWidest = width;
   return width;
 }
 protected int getHeight(int i) {
   int height = 0;
   String heightString = getParameter("HEIGHT" + i);
   if (heightString != null) {
     try {
       height = Integer.parseInt(heightString);
     } catch (NumberFormatException e) {
       height = 0;
     }
   } else {
     height = 0;
   }
   if (height > heightOfTallest)
     heightOfTallest = height;
   return height;
 }
 public String[][] getParameterInfo() {
   String[][] info = {
       { "IMAGEDIR", "string", "directory containing image files" },
       { "IMAGEN", "string", "filename" },
       { "CAPTIONN", "string", "caption" },
       { "WIDTHN", "integer", "width of image" },
       { "HEIGHTN", "integer", "height of image" }, };
   return info;
 }

} class Photo {

 public String filename;
 public String caption;
 public int width;
 public int height;
 public ImageIcon icon;
 public Photo(String filename, String caption, int w, int h) {
   this.filename = filename;
   if (caption == null)
     this.caption = filename;
   else
     this.caption = caption;
   width = w;
   height = h;
   icon = null;
 }
 public void setIcon(ImageIcon i) {
   icon = i;
 }
 public ImageIcon getIcon() {
   return icon;
 }

} /**

* This is the 3rd version of SwingWorker (also known as SwingWorker 3), an
* abstract class that you subclass to perform GUI-related work in a dedicated
* thread. For instructions on and examples of using this class, see:
* 
* http://java.sun.ru/docs/books/tutorial/uiswing/misc/threads.html
* 
* Note that the API changed slightly in the 3rd version: You must now invoke
* start() on the SwingWorker after creating it.
*/

abstract class SwingWorker {

 private Object value; // see getValue(), setValue()
 /**
  * Class to maintain reference to current worker thread under separate
  * synchronization control.
  */
 private static class ThreadVar {
   private Thread thread;
   ThreadVar(Thread t) {
     thread = t;
   }
   synchronized Thread get() {
     return thread;
   }
   synchronized void clear() {
     thread = null;
   }
 }
 private ThreadVar threadVar;
 /**
  * Get the value produced by the worker thread, or null if it hasn"t been
  * constructed yet.
  */
 protected synchronized Object getValue() {
   return value;
 }
 /**
  * Set the value produced by worker thread
  */
 private synchronized void setValue(Object x) {
   value = x;
 }
 /**
  * Compute the value to be returned by the get method.
  */
 public abstract Object construct();
 /**
  * Called on the event dispatching thread (not on the worker thread) after
  * the construct method has returned.
  */
 public void finished() {
 }
 /**
  * A new method that interrupts the worker thread. Call this method to force
  * the worker to stop what it"s doing.
  */
 public void interrupt() {
   Thread t = threadVar.get();
   if (t != null) {
     t.interrupt();
   }
   threadVar.clear();
 }
 /**
  * Return the value created by the construct method. Returns
  * null if either the constructing thread or the current thread was
  * interrupted before a value was produced.
  * 
  * @return the value created by the construct method
  */
 public Object get() {
   while (true) {
     Thread t = threadVar.get();
     if (t == null) {
       return getValue();
     }
     try {
       t.join();
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt(); // propagate
       return null;
     }
   }
 }
 /**
  * Start a thread that will call the construct method and
  * then exit.
  */
 public SwingWorker() {
   final Runnable doFinished = new Runnable() {
     public void run() {
       finished();
     }
   };
   Runnable doConstruct = new Runnable() {
     public void run() {
       try {
         setValue(construct());
       } finally {
         threadVar.clear();
       }
       SwingUtilities.invokeLater(doFinished);
     }
   };
   Thread t = new Thread(doConstruct);
   threadVar = new ThreadVar(t);
 }
 /**
  * Start the worker thread.
  */
 public void start() {
   Thread t = threadVar.get();
   if (t != null) {
     t.start();
   }
 }

}


 </source>
   
  
 
  



Image Loader Applet

   <source lang="java">
 

/* Java Media APIs: Cross-Platform Imaging, Media and Visualization Alejandro Terrazas Sams, Published November 2002, ISBN 0672320940

  • /

import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; import java.awt.image.ImageObserver; import java.net.MalformedURLException; import java.net.URL; import javax.swing.JFrame; /**

* ImageLoaderApplet.java -- load and display image specified by imageURL
*/

public class ImageLoaderApplet extends Applet {

 private Image img;
 private String imageURLString = "peppers.png";
 public void init() {
   URL url;
   try {
     // set imageURL here
     url = new URL(imageURLString);
     img = getImage(url);
   } catch (MalformedURLException me) {
     showStatus("Malformed URL: " + me.getMessage());
   }
 }
 /**
  * overloaded method to prevent clearing drawing area
  */
 public void update(Graphics g) {
   paint(g);
 }
 public void paint(Graphics g) {
   g.drawImage(img, 0, 0, this);
 }
 /**
  * Verbose version of ImageConsumer"s imageUpdate method
  */
 public boolean imageUpdate(Image img, int flags, int x, int y, int width,
     int height) {
   System.out.print("Flag(s): ");
   if ((flags & ImageObserver.WIDTH) != 0) {
     System.out.print("WIDTH:(" + width + ") ");
   }
   if ((flags & ImageObserver.HEIGHT) != 0) {
     System.out.print("HEIGHT:(" + height + ") ");
   }
   if ((flags & ImageObserver.PROPERTIES) != 0) {
     System.out.print("PROPERTIES ");
   }
   if ((flags & ImageObserver.SOMEBITS) != 0) {
     System.out.print("SOMEBITS(" + x + "," + y + ")->(");
     System.out.print(width + "," + height + ") ");
     repaint();
   }
   if ((flags & ImageObserver.FRAMEBITS) != 0) {
     System.out.print("FRAMEBITS(" + x + "," + y + ")->(");
     System.out.print(width + "," + height + ") ");
     repaint();
   }
   if ((flags & ImageObserver.ALLBITS) != 0) {
     System.out.print("ALLBITS(" + x + "," + y + ")->(");
     System.out.println(width + "," + height + ") ");
     repaint();
     return false;
   }
   if ((flags & ImageObserver.ABORT) != 0) {
     System.out.println("ABORT \n");
     return false;
   }
   if ((flags & ImageObserver.ERROR) != 0) {
     System.out.println("ERROR ");
     return false;
   }
   System.out.println();
   return true;
 }
 public static void main(String[] argv) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   ImageLoaderApplet a = new ImageLoaderApplet();
   frame.getContentPane().add(a);
   frame.setSize(300, 300);
   a.init();
   a.start();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Java Applets Can Run CGI"s (on some browsers)

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <html> <head>

 <title>Java Applets Can Run CGI"s (on some browsers)</title>

</head> <body bgcolor="white">

Java Applets Can Run CGI"s (on some browsers)

Click on the button on this little Applet for p(r)oof!

<applet code="TryCGI" width="100" height="30">

If you can see this, you need to get a Java-powered(tm) Web Browser before you can watch for real.

</applet>


Use , Luke.

</body> </html>

  • /

import java.applet.Applet; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; /**

* Try running a CGI-BIN script from within Java.
*/

public class TryCGI extends Applet implements ActionListener {

 protected Button goButton;
 public void init() {
   add(goButton = new Button("Go for it!"));
   goButton.addActionListener(this);
 }
 public void actionPerformed(ActionEvent evt) {
   try {
     URL myNewURL = new URL("http://server/cgi-bin/credit");
     // debug...
     System.out.println("URL = " + myNewURL);
     // "And then a miracle occurs..."
     getAppletContext().showDocument(myNewURL);
   } catch (Exception err) {
     System.err.println("Error!\n" + err);
     showStatus("Error, look in Java Console for details!");
   }
 }

}



 </source>
   
  
 
  



Java Wave Applet Demo

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <HTML><HEAD><TITLE>Java Wave Applet Demo</TITLE></HEAD> <BODY BGCOLOR=Black TEXT=White Link=White VLink=White>

Java Wave Applet Demo

Wave Applet

This is a very simple applet that draws the sum of a sine and a cosine wave.


<P>And here is the demo:


<APPLET code="Wavelet" width=500 height=200> <P>This applet will only work if you"re viewing it with a Java-1.1-enabled browser.<P> </APPLET>


<P>Here is the .


<address>http://www.darwinsys.ru/,</address> adapted from code by <address>avh@eng.sun.ru </address> </BODY> </HEAD>

  • /

import java.applet.Applet; import java.awt.Dimension; import java.awt.Graphics; /**

* Simple Applet demo, showing a math function.
* 
* @author Arthur Van Hoff, avh
* @author Ian F. Darwin, http://www.darwinsys.ru/
*/

public class Wavelet extends Applet {

 /**
  * Called by AWT when the window needs painting; just recompute all the data
  * and draw it, since it"s a simple calculation and simpler than
  * precomputing and storing the data.
  */
 public void paint(Graphics g) {
   Dimension d = getSize();
   for (int x = 0; x < d.width; x++) {
     g.drawLine(x, 20 + (int) func(x), x + 1, 20 + (int) func(x + 1));
   }
 }
 /** This is the function that is plotted. */
 double func(double x) {
   Dimension d = getSize();
   return (Math.cos(x / 9) + Math.sin(x / 3) + 1) * d.height / 4;
 }

}


 </source>
   
  
 
  



JDBC applet

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/**

* This is a demonstration JDBC applet. It displays some simple standard output
* from the Coffee database.
*/

import java.applet.Applet; import java.awt.Graphics; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; public class OutputApplet extends Applet implements Runnable {

 private Thread worker;
 private Vector queryResults;
 private String message = "Initializing";
 public synchronized void start() {
   // Every time "start" is called we create a worker thread to
   // re-evaluate the database query.
   if (worker == null) {
     message = "Connecting to database";
     worker = new Thread(this);
     worker.start();
   }
 }
 /**
  * The "run" method is called from the worker thread. Notice that because
  * this method is doing potentially slow databases accesses we avoid making
  * it a synchronized method.
  */
 public void run() {
   String url = "jdbc:mySubprotocol:myDataSource";
   String query = "select COF_NAME, PRICE from COFFEES";
   try {
     Class.forName("myDriver.ClassName");
   } catch (Exception ex) {
     setError("Can"t find Database driver class: " + ex);
     return;
   }
   try {
     Vector results = new Vector();
     Connection con = DriverManager.getConnection(url, "myLogin",
         "myPassword");
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(query);
     while (rs.next()) {
       String s = rs.getString("COF_NAME");
       float f = rs.getFloat("PRICE");
       String text = s + "     " + f;
       results.addElement(text);
     }
     stmt.close();
     con.close();
     setResults(results);
   } catch (SQLException ex) {
     setError("SQLException: " + ex);
   }
 }
 /**
  * The "paint" method is called by AWT when it wants us to display our
  * current state on the screen.
  */
 public synchronized void paint(Graphics g) {
   // If there are no results available, display the current message.
   if (queryResults == null) {
     g.drawString(message, 5, 50);
     return;
   }
   // Display the results.
   g.drawString("Prices of coffee per pound:  ", 5, 10);
   int y = 30;
   java.util.Enumeration e = queryResults.elements();
   while (e.hasMoreElements()) {
     String text = (String) e.nextElement();
     g.drawString(text, 5, y);
     y = y + 15;
   }
 }
 /**
  * This private method is used to record an error message for later display.
  */
 private synchronized void setError(String mess) {
   queryResults = null;
   message = mess;
   worker = null;
   // And ask AWT to repaint this applet.
   repaint();
 }
 /**
  * This private method is used to record the results of a query, for later
  * display.
  */
 private synchronized void setResults(Vector results) {
   queryResults = results;
   worker = null;
   // And ask AWT to repaint this applet.
   repaint();
 }

}


 </source>
   
  
 
  



Load resource in Applet

Passing Parameters to Java Applet

   <source lang="java">
 

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Label; public class Main extends Applet {

 Label m_titleLabel = new Label(getParameter("Title"));
 public void init() {
   setLayout(new BorderLayout());
   add(BorderLayout.NORTH, m_titleLabel);
 }

}

<HTML> <TITLE> Writing and Running Java Applet, Demonstration </TITLE> <BODY> <APPLET CODE="ParamApplet.class" WIDTH=600 HEIGHT=275 > <PARAM NAME=Title VALUE="This is a Title String"> </APPLET> </BODY> </HTML>


 </source>
   
  
 
  



Read an applet parameters

   <source lang="java">
 

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Main extends Applet {

 private String name = "";
 public void init() {
   name = getParameter("name");
 }
 public void paint(Graphics g) {
   g.setColor(Color.BLUE);
   g.drawString(name, 0, 0);
 }

}

To enable the web browser to execute the applet create the following html page. <html> <head>

 <title>Parameterized Applet</title>

</head> <body>

   <applet code="Main" height="150" width="350">
       <param name="name" value="abc" />
   </applet>

</body> </html>


 </source>
   
  
 
  



Scribble Applet

   <source lang="java">
 

/*

* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O"Reilly & Associates.  
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained.  Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/

import java.applet.*; import java.awt.*; /** A simple applet using the Java 1.0 event handling model */ public class Scribble extends Applet {

 private int lastx, lasty;    // Remember last mouse coordinates.
 Button erase_button;         // The Erase button.
 Graphics g;                  // A Graphics object for drawing.
 /** Initialize the button and the Graphics object */
 public void init() {
   erase_button = new Button("Erase");
   this.add(erase_button);
   g = this.getGraphics();
   this.requestFocus();  // Ask for keyboard focus so we get key events
 }
 /** Respond to mouse clicks */
 public boolean mouseDown(Event e, int x, int y) {
   lastx = x; lasty = y;             // Remember where the click was
   return true;
 }
 /** Respond to mouse drags */
 public boolean mouseDrag(Event e, int x, int y) {
   g.setColor(Color.black);
   g.drawLine(lastx, lasty, x, y);   // Draw from last position to here
   lastx = x; lasty = y;             // And remember new last position
   return true;
 }
 /** Respond to key presses: Erase drawing when user types "e" */
 public boolean keyDown(Event e, int key) {
   if ((e.id == Event.KEY_PRESS) && (key == "e")) {
     g.setColor(this.getBackground());   
     g.fillRect(0, 0, bounds().width, bounds().height);
     return true;
   }
   else return false;
 }
 /** Respond to Button clicks: erase drawing when user clicks button */
 public boolean action(Event e, Object arg) {
   if (e.target == erase_button) {
     g.setColor(this.getBackground());   
     g.fillRect(0, 0, bounds().width, bounds().height);
     return true;
   }
   else return false;
 }

}



 </source>
   
  
 
  



ShowDocApplet: try out showDocument()

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <HEAD> <TITLE>ShowDocApplet: try out showDocument().</TITLE> </HEAD> <BODY BGCOLOR=PINK>

ShowDocApplet: try out showDocument().

<APPLET CODE=ShowDocApplet.java WIDTH=300 HEIGHT=200> </APPLET> </BODY>

  • /

import java.applet.Applet; import java.awt.Button; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.MalformedURLException; import java.net.URL; /**

* ShowDocApplet: Demonstrate showDocument().
* 
* @author Ian Darwin, http://www.darwinsys.ru/
*/

public class ShowDocApplet extends Applet {

 // String targetString = "http://www.darwinsys.ru/javacook/secret.html";
 String targetString = "file:///c:/javasrc/network/ShowDocApplet.java";
 /** The URL to go to */
 URL targetURL;
 /** Initialize the Applet */
 public void init() {
   setBackground(Color.gray);
   try {
     targetURL = new URL(targetString);
   } catch (MalformedURLException mfu) {
     throw new IllegalArgumentException("ShowDocApplet got bad URL "
         + targetString);
   }
   Button b = new Button("View Secret");
   add(b);
   b.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       getAppletContext().showDocument(targetURL);
     }
   });
 }
 public void stop() {
   System.out.println("Ack! Its been fun being an Applet. Goodbye!");
 }

}


 </source>
   
  
 
  



Show Document

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.applet.Applet; import java.applet.AppletContext; import java.awt.Button; import java.awt.Choice; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.MalformedURLException; import java.net.URL; public class ShowDocument extends Applet implements ActionListener {

 URLWindow urlWindow;
 public void init() {
   Button button = new Button("Bring up URL window");
   button.addActionListener(this);
   add(button);
   urlWindow = new URLWindow(getAppletContext());
   urlWindow.pack();
 }
 public void destroy() {
   urlWindow.setVisible(false);
   urlWindow = null;
 }
 public void actionPerformed(ActionEvent event) {
   urlWindow.setVisible(true);
 }

} class URLWindow extends Frame implements ActionListener {

 TextField urlField;
 Choice choice;
 AppletContext appletContext;
 public URLWindow(AppletContext appletContext) {
   super("Show a Document!");
   this.appletContext = appletContext;
   GridBagLayout gridBag = new GridBagLayout();
   GridBagConstraints c = new GridBagConstraints();
   setLayout(gridBag);
   Label label1 = new Label("URL of document to show:", Label.RIGHT);
   gridBag.setConstraints(label1, c);
   add(label1);
   urlField = new TextField("http://java.sun.ru/", 40);
   urlField.addActionListener(this);
   c.gridwidth = GridBagConstraints.REMAINDER;
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 1.0;
   gridBag.setConstraints(urlField, c);
   add(urlField);
   Label label2 = new Label("Window/frame to show it in:", Label.RIGHT);
   c.gridwidth = 1;
   c.weightx = 0.0;
   gridBag.setConstraints(label2, c);
   add(label2);
   choice = new Choice();
   choice.addItem("(browser"s choice)"); //don"t specify
   choice.addItem("My Personal Window"); //a window named
   //"My Personal Window"
   choice.addItem("_blank"); //a new, unnamed window
   choice.addItem("_self");
   choice.addItem("_parent");
   choice.addItem("_top"); //the Frame that contained this
   //applet
   c.fill = GridBagConstraints.NONE;
   c.gridwidth = GridBagConstraints.REMAINDER;
   c.anchor = GridBagConstraints.WEST;
   gridBag.setConstraints(choice, c);
   add(choice);
   Button button = new Button("Show document");
   button.addActionListener(this);
   c.weighty = 1.0;
   c.ipadx = 10;
   c.ipady = 10;
   c.insets = new Insets(5, 0, 0, 0);
   c.anchor = GridBagConstraints.SOUTH;
   gridBag.setConstraints(button, c);
   add(button);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent event) {
       setVisible(false);
     }
   });
 }
 public void actionPerformed(ActionEvent event) {
   String urlString = urlField.getText();
   URL url = null;
   try {
     url = new URL(urlString);
   } catch (MalformedURLException e) {
     System.err.println("Malformed URL: " + urlString);
   }
   if (url != null) {
     if (choice.getSelectedIndex() == 0) {
       appletContext.showDocument(url);
     } else {
       appletContext.showDocument(url, choice.getSelectedItem());
     }
   }
 }

} //<applet code="ShowDocument.class" width=200 height=30> //</applet>



 </source>
   
  
 
  



Signed Applet

Slide Puzzle

   <source lang="java">
 

import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Rectangle; /* SlidePuzzle, originally from VisualJ++ Developer"s News, July 1997 */ public class SlidePuzzle extends Applet implements Runnable {

 Thread m_SlidePuzzle = null;
 private Graphics m_Graphics;
 private Image logo;
 private boolean m_fAllLoaded = false;
 private Rectangle squares[];
 private int order[];
 private int x = 1;
 private int y = 0;
 public void init() {
   //Define and populate Rectangle array
   squares = new Rectangle[9];
   squares[0] = new Rectangle(0, 0, 60, 60);
   squares[1] = new Rectangle(0, 60, 60, 60);
   squares[2] = new Rectangle(0, 120, 60, 60);
   squares[3] = new Rectangle(60, 0, 60, 60);
   squares[4] = new Rectangle(60, 60, 60, 60);
   squares[5] = new Rectangle(60, 120, 60, 60);
   squares[6] = new Rectangle(120, 0, 60, 60);
   squares[7] = new Rectangle(120, 60, 60, 60);
   squares[8] = new Rectangle(120, 120, 60, 60);
   //Define and populate int array
   order = new int[9];
   order[0] = 6;
   order[1] = 2;
   order[2] = 8;
   order[3] = 1;
   order[4] = 0;
   order[5] = 7;
   order[6] = 5;
   order[7] = 4;
   order[8] = 3;
 }
 public void paint(Graphics g) {
   if (m_fAllLoaded) {
     Rectangle r = g.getClipRect();
     g.clearRect(r.x, r.y, r.width, r.height);
     g.drawImage(logo, 0, 0, null);
   } else
     g.drawString("Loading images...", 10, 20);
 }
 public void start() {
   if (m_SlidePuzzle == null) {
     m_SlidePuzzle = new Thread(this);
     m_SlidePuzzle.start();
   }
 }
 public void stop() {
   if (m_SlidePuzzle != null) {
     m_SlidePuzzle.stop();
     m_SlidePuzzle = null;
   }
 }
 public void run() {
   if (!m_fAllLoaded) {
     m_Graphics = getGraphics();
     MediaTracker tracker = new MediaTracker(this);
     logo = getImage(getDocumentBase(), "vjlogo.gif");
     tracker.addImage(logo, 0);
     try {
       tracker.waitForAll();
       m_fAllLoaded = !tracker.isErrorAny();
     } catch (InterruptedException e) {
     }
     if (!m_fAllLoaded) {
       stop();
       m_Graphics.drawString("Error loading images!", 10, 40);
       return;
     }
   }
   //Clear the screen and draw first image
   repaint();
   //Move the squares
   while (true) {
     for (x = 1; x < 9; x++) {
       //Slow down the animation
       try {
         Thread.sleep(350);
       } catch (InterruptedException e) {
       }
       //Move square to next location
       m_Graphics.copyArea(squares[order[x]].x, squares[order[x]].y,
           60, 60, squares[order[x - 1]].x - squares[order[x]].x,
           squares[order[x - 1]].y - squares[order[x]].y);
       //Clear most recently copied square
       m_Graphics.clearRect(squares[order[x]].x, squares[order[x]].y,
           60, 60);
     }
     //Repaint original graphic after two cycles
     y++;
     if (y == 2) {
       repaint();
       y = 0;
     }
   }
 }

}


 </source>
   
  
 
  



Socket Applet

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

/*

* 1.1 version.
*/

import java.io.*; import java.net.*; import java.util.*; class TalkServerThread extends Thread {

   public Socket socket;
   public BufferedReader is;
   public BufferedWriter os;
   TalkServer server;
   boolean DEBUG = false;
   public String toString() {
       return "TalkServerThread: socket = " + socket
              + "; is = " + is
              + "; os = " + os;
   }
   TalkServerThread(Socket socket, TalkServer server) throws IOException {
       super("TalkServer");
       is = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));
       os = new BufferedWriter(
    new OutputStreamWriter(socket.getOutputStream()));
       if (is == null) {
           System.err.println("TalkServerThread: Input stream seemed "
                              + "to be created successfully, but it"s null.");
           throw new IOException();
       }
       if (os == null) {
           System.err.println("TalkServerThread: Output stream seemed "
                              + "to be created successfully, but it"s null.");
           throw new IOException();
       }
       this.socket = socket;
       this.server = server;
   }
   public void run() {
       while (socket != null) {
           try {
               //Read data.
               String str = is.readLine();
               //Pass it on.
               if (str != null) {
                   server.forwardString(str, this);
               }
           } catch (EOFException e) { //No more data on this socket...
               server.forwardString("SERVER SAYS other applet disconnected",
                                    this);
               cleanup();
               return;
           } catch (NullPointerException e) { //Socket doesn"t exist...
               server.forwardString("SERVER SAYS no socket to other applet",
                                    this);
               cleanup();
               return;
           } catch (IOException e) { //Read problem..
               server.forwardString("SERVER SAYS socket trouble with other applet",
                                    this);
               cleanup();
               return;
           } catch (Exception e) { //Unknown exception. Complain and quit.
               System.err.println("Exception on is.readLine():");
               e.printStackTrace();
               cleanup();
               return;
           }
       }
   }
   protected void finalize() {
       cleanup();
   }
   void cleanup() {
       try {
           if (is != null) {
               is.close();
               is = null;
           }
       } catch (Exception e) {} //Ignore errors.
       try {
           if (os != null) {
               os.close();
               os = null;
           }
       } catch (Exception e) {} //Ignore errors.
       try {
           if (socket != null) {
               socket.close();
               socket = null;
           }
       } catch (Exception e) {} //Ignore errors.
   }

}


/*

* 1.1 version.
*/

import java.net.*; import java.io.*; class TalkServer {

   TalkServerThread[] tstList = new TalkServerThread[2];
   boolean DEBUG = false;
   public static void main(String[] args) {
       new TalkServer().start();
   }
   public void start() {
       ServerSocket serverRSocket = null;
       int numConnected = 0;
       try {
           serverRSocket = new ServerSocket(0);
           System.out.println("TalkServer listening on rendezvous port: "
                              + serverRSocket.getLocalPort());
       } catch (IOException e) {
           System.err.println("Server could not create server socket for rendezvous.");
           return;
       }
       while (true) {
           //Connect to two clients.
           while (numConnected < 2) {
               TalkServerThread tst;
               tst = connectToClient(serverRSocket);
               if (tst != null) {
                   numConnected++;
                   if (tstList[0] == null) {
                       tstList[0] = tst;
                   } else {
                       tstList[1] = tst;
                   }
               }
           } //end while (numConnected < 2) loop
           if (DEBUG) {
               try {
                   System.out.println("tst #0 = " + tstList[0]);
               } catch (Exception e) {}
               try {
                   System.out.println("tst #1 = " + tstList[1]);
               } catch (Exception e) {}
           }
           //If they"re really OK, tell them to start writing.
           if (everythingIsOK(0) & everythingIsOK(1)) {
               for (int i = 0; i < 2; i++) {
                   writeToStream("START WRITING!\n----------------------"
                                 + "-------------", tstList[i].os);
               }
           } else {
               System.err.println("2 server threads created, but "
                                  + "not everything is OK");
           }
           while (numConnected == 2) {
               if (!everythingIsOK(0)) {
                   if (DEBUG) {
                       System.out.println("Applet #0 is hosed; disconnecting.");
                   }
                   numConnected--;
                   cleanup(tstList[0]);
                   tstList[0] = null;
               }
               if (!everythingIsOK(1)) {
                   if (DEBUG) {
                       System.out.println("Applet #1 is hosed; disconnecting.");
                   }
                   numConnected--;
                   cleanup(tstList[1]);
                   tstList[1] = null;
               }
                      try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
               } 
           } //end while(numConnected==2) loop
           if (DEBUG) {
               try {
                   System.out.println("Number of connections = " + numConnected);
                   System.out.println("tst #0 = " + tstList[0]);
                   System.out.println("tst #1 = " + tstList[1]);
               } catch (Exception e) {}
           }
       } //end while (true) loop
   }
   protected TalkServerThread connectToClient(ServerSocket serverRSocket) {
       Socket rendezvousSocket = null;
       TalkServerThread tst = null;
       //Listen for client connection on the rendezvous socket.
       try {
           rendezvousSocket = serverRSocket.accept();
       } catch (IOException e) {
           System.err.println("Accept failed.");
           e.printStackTrace();
           return null;
       }
       //Create a thread to handle this connection.
       try {
           tst = new TalkServerThread(rendezvousSocket, this);
           tst.start();
       } catch (Exception e) {
            System.err.println("Couldn"t create TalkServerThread:");
           e.printStackTrace();
           return null;
       }
       writeToStream("Successful connection. "
                     + "Please wait for second applet to connect...",
                     tst.os);
       return tst;
   }
   boolean everythingIsOK(int tstNum) {
       TalkServerThread tst = tstList[tstNum];
       if (tst == null) {
           if (DEBUG) {
               System.out.println("TalkServerThread #" + tstNum
                                  + " is null");
           }
           return false;
       } else {
           if (tst.os == null) {
               if (DEBUG) {
                   System.out.println("TalkServerThread #" + tstNum
                                      + " output stream is null.");
               }
               return false;
           }
           if (tst.is == null) {
               if (DEBUG) {
                   System.out.println("TalkServerThread #" + tstNum
                                      + " input stream is null.");
               }
               return false;
           }
           if (tst.socket == null) {
               if (DEBUG) {
                   System.out.println("TalkServerThread #" + tstNum
                                      + " socket is null.");
               }
               return false;
           }
       }
       return true;
   }
   void cleanup(TalkServerThread tst) {
       if (tst != null) {
           try {
               if (tst.os != null) {
                   tst.os.close();
                   tst.os = null;
               }
           } catch (Exception e) {} //Ignore errors
           try {
               if (tst.is != null) {
                   tst.is.close();
                   tst.is = null;
               }
           } catch (Exception e) {} //Ignore errors
           try {
               if (tst.socket != null) {
                   tst.socket.close();
                   tst.socket = null;
               }
           } catch (Exception e) {} //Ignore errors
       }
   }
   public void forwardString(String string, TalkServerThread requestor) {
       BufferedWriter clientStream = null;
       if (tstList[0] == requestor) {
           if (tstList[1] != null) {
               clientStream = tstList[1].os;
           } else {
               if (DEBUG) {
                   System.out.println("Applet #0 has a string to forward, "
                                      + "but Applet #1 is gone...");
               }
               return;
           }
       } else {
           if (tstList[0] != null) {
               clientStream = tstList[0].os;
           } else {
               if (DEBUG) {
                   System.out.println("Applet #1 has a string to forward, "
                                      + "but Applet #0 is gone...");
               }
               return;
           }
       }
       if (clientStream != null) {
           writeToStream(string, clientStream);   
       } else if (DEBUG) {
           System.out.println("Can"t forward string -- no output stream.");
       }
   }
   public void writeToStream(String string, BufferedWriter stream) {
       if (DEBUG) {
           System.out.println("TalkServer about to forward data: "
                              + string);
       }
       try { 
           stream.write(string);
     stream.newLine();
           stream.flush();
           if (DEBUG) {
               System.out.println("TalkServer forwarded string.");
           }
       } catch (IOException e) {
           System.err.println("TalkServer failed to forward string:");
           e.printStackTrace();
           return;
       } catch (NullPointerException e) {
           System.err.println("TalkServer can"t forward string "
                              + "since output stream is null.");
           return;
       }
   }

}

/*

* 1.1 version.
*/

import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; public class TalkClientApplet extends Applet

             implements Runnable,
            ActionListener {
   Socket socket;
   BufferedWriter os;
   BufferedReader is;
   TextField portField, message;
   TextArea display;
   Button button;
   int dataPort;
   boolean trysted;
   Thread receiveThread;
   String host;
   boolean DEBUG = false;
   String newline;
   public void init() {
       //Get the address of the host we came from.
       host = getCodeBase().getHost();
       //Set up the UI.
       GridBagLayout gridBag = new GridBagLayout();
       GridBagConstraints c = new GridBagConstraints();
       setLayout(gridBag);
       message = new TextField("");
       c.fill = GridBagConstraints.HORIZONTAL;
       c.gridwidth = GridBagConstraints.REMAINDER;
       gridBag.setConstraints(message, c); 
 message.addActionListener(this);
       add(message);
       display = new TextArea(10, 40);
       display.setEditable(false);
       c.weightx = 1.0;
       c.weighty = 1.0;
       c.fill = GridBagConstraints.BOTH;
       gridBag.setConstraints(display, c); 
       add(display);
       Label l = new Label("Enter the port (on host " + host
                           + ") to send the request to:", 
                           Label.RIGHT);
       c.fill = GridBagConstraints.HORIZONTAL;
       c.gridwidth = 1;
       c.weightx = 0.0;
       c.weighty = 0.0;
       gridBag.setConstraints(l, c); 
       add(l);
       portField = new TextField(6);
       c.fill = GridBagConstraints.NONE;
       gridBag.setConstraints(portField, c); 
 portField.addActionListener(this);
       add(portField);
       button = new Button("Connect");
       gridBag.setConstraints(button, c); 
 button.addActionListener(this);
       add(button);
 newline = System.getProperty("line.separator");
   }
   public synchronized void start() {
       if (DEBUG) {
           System.out.println("In start() method.");
       }
       if (receiveThread == null) {
           trysted = false;
           portField.setEditable(true);
           button.setEnabled(true);
           os = null;
           is = null;
           socket = null;
           receiveThread = new Thread(this);
           receiveThread.start();
           if (DEBUG) {
               System.out.println("  Just set everything to null and started thread.");
           }
       } else if (DEBUG) {
           System.out.println("  receiveThread not null! Did nothing!");
       }
   }
   public synchronized void stop() {
       if (DEBUG) {
           System.out.println("In stop() method.");
       }
       receiveThread = null;
       trysted = false;
       portField.setEditable(true);
       button.setEnabled(true);
       notify();
       try { //Close input stream.
           if (is != null) {
               is.close();
               is = null;
           }
       } catch (Exception e) {} //Ignore exceptions.
       try { //Close output stream.
           if (os != null) {
               os.close();
               os = null;
           }
       } catch (Exception e) {} //Ignore exceptions.
       try { //Close socket.
           if (socket != null) {
               socket.close();
               socket = null;
           }
       } catch (Exception e) {} //Ignore exceptions.
   }
           
   public Insets getInsets() {
       return new Insets(4,4,5,5);
   }
   public void paint(Graphics g) {
       Dimension d = getSize();
       Color bg = getBackground();
       g.setColor(bg);
       g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
       g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
   }
   public synchronized void actionPerformed(ActionEvent event) {
       int port;
       
       if (DEBUG) {
           System.out.println("In action() method.");
       }
       if (receiveThread == null) {
           start();
       }
       if (!trysted) {
       //We need to attempt a rendezvous.
           if (DEBUG) {
               System.out.println("  trysted = false. "
                                  + "About to attempt a rendezvous.");
           }
           //Get the port the user entered...
           try {
               port = Integer.parseInt(portField.getText());
           } catch (NumberFormatException e) {
               //No integer entered. 
               display.append("Please enter an integer below."
            + newline);
               return;
           }
           //...and rendezvous with it.
           rendezvous(port);
       } else { //We"ve already rendezvoused. Just send data over.
           if (DEBUG) {
               System.out.println("  trysted = true. "
                                  + "About to send data.");
           }
           String str = message.getText();
           message.selectAll();
           try {
               os.write(str);
   os.newLine();
               os.flush();
           } catch (IOException e) {
               display.append("ERROR: Applet couldn"t write to socket."
            + newline);
               display.append("...Disconnecting."
            + newline);
               stop();
               return;
           } catch (NullPointerException e) {
               display.append("ERROR: No output stream!"
            + newline);
               display.append("...Disconnecting."
            + newline);
               stop();
               return;
           }
           display.append("Sent: " + str + newline);
       }
   }
   synchronized void waitForTryst() {
       //Wait for notify() call from action().
       try {
           wait();        
       } catch (InterruptedException e) {}
       if (DEBUG) {
           System.out.println("waitForTryst about to return. "
                              + "trysted = " + trysted + ".");
       }
       return;
   }
   public void run() {
       String received = null;
       waitForTryst();
       //OK, now we can send messages.
       while (Thread.currentThread() == receiveThread) {
           try { 
               //Wait for data from the server.
               received = is.readLine();
               //Display it.
               if (received != null) {
                   display.append("Received: " + received 
          + newline);
               } else { //success but no data...
                   System.err.println("End of stream?");
       return; //XXX
               }
           } catch (IOException e) { //Perhaps a temporary problem?
               display.append("NOTE: Couldn"t read from socket.\n");
               return;
           }
       }
   }
   private void rendezvous(int port) {
       //Try to open a socket to the port.
       try {
           socket = new Socket(host, port);
       } catch (UnknownHostException e) {
           display.append("ERROR: Can"t find host: " + host
        + newline);
           return;
       } catch (IOException e) {
           display.append("ERROR: Can"t open socket on rendezvous port "
                          + port + " (on host " + host + ")."
        + newline);
           return;
       }
       //Try to open streams to read and write from the socket.
       try {
           os = new BufferedWriter(
        new OutputStreamWriter(socket.getOutputStream()));
           is = new BufferedReader(
        new InputStreamReader(socket.getInputStream()));
       } catch (IOException e) {
           display.append("ERROR: Created data socket but can"t "
                          + "open stream on it."
        + newline);
           display.append("...Disconnecting." + newline);
           stop();
           return;
       }   
       if ((os != null) & (is != null)) {
           if (DEBUG) {
               System.out.println("Successful rendezvous.");
               System.out.println("socket = " + socket);
               System.out.println("output stream = " + os);
               System.out.println("input stream = " + is);
           }
           //Let the main applet thread know we"ve successfully rendezvoused.
           portField.setEditable(false);
           button.setEnabled(false);
           trysted = true;
           notify();
       } else {
           display.append("ERROR: Port is valid but communication failed. "
                          + "Please TRY AGAIN." + newline);
       }
   }

}


 </source>
   
  
 
  



This applet is a simple button that plays an audio clip when pushed

   <source lang="java">
  

/*

  • Copyright (c) 1996, 1998 Bill Venners. All Rights Reserved.
  • Source code file for the Whistle applet, part of the article
  • "Impressions of SD "98" by Bill Venners, published
  • in JavaWorld March, 1998
  • This source file may not be copied, modified, or redistributed
  • EXCEPT as allowed by the following statements: You may freely use
  • this file for your own work, including modifications and
  • distribution in compiled (class files, native executable, etc.)
  • form only. You may not copy and distribute this file. You may not
  • remove this copyright notice. You may not distribute modified
  • versions of this source file. You may not use this file in printed
  • media without the express permission of Bill Venners.
  • BILL VENNERS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
  • SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
  • BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
  • FITNESS FOR PARTICULAR PURPOSE, OR NON-INFRINGEMENT. BILL VENNERS
  • SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY A LICENSEE AS A
  • RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
  • DERIVATIVES.
  • /

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Label; import java.applet.AudioClip; import java.awt.Event; import java.net.URL; import java.net.URLConnection; import java.net.MalformedURLException;

/**

  • This applet is a simple button that plays an audio clip when
  • pushed.
  • @author Bill Venners
  • /

public class Whistle extends java.applet.Applet implements Runnable {

   URL theURL;
   private AudioClip yeehaa;
   private Thread runner;
   private boolean startClip = false;
   private boolean urlExceptionWasThrown = false;
   public void start() {
       if (runner == null) {
           runner = new Thread(this);
           runner.start();
       }
   }
   public void stop() {
       if (runner != null) {
           if (yeehaa != null) {
               yeehaa.stop();
           }
           runner.stop();
           runner = null;
       }
   }
   public void init() {
       super.init();
       String url = getParameter("clipURL");
       try {
           theURL = new URL(getDocumentBase(), url);
       }
       catch (MalformedURLException e) {
           urlExceptionWasThrown = true;
       }
       if (!urlExceptionWasThrown) {
           yeehaa = getAudioClip(theURL);
           setLayout(new BorderLayout());
           add("Center", new Button("Whistle"));
       }
       else {
           setLayout(new BorderLayout());
           add("Center", new Label("Sorry, No Audio"));
       }
   }
   public void run() {
       while (runner != null) {
           if (startClip && yeehaa != null) {
               startClip = false;
               yeehaa.play();
           }
           try {
               Thread.sleep(500);
           }
           catch (InterruptedException e) {
           }
       }
   }
   public boolean action(Event evt, Object arg) {
       if (evt.target instanceof Button) {
           String bname = (String) arg;
           if (bname.equals("Whistle")) {
               startClip = true;
           }
       }
       return true;
   }

}


 </source>
   
  
 
  



Thread Race Applet

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JApplet; import javax.swing.JPanel; public class RaceApplet extends JApplet implements Runnable {

 private final static int NUMRUNNERS = 2;
 private final static int SPACING = 20;
 private Runner[] runners = new Runner[NUMRUNNERS];
 private Thread updateThread = null;
 public void init() {
   String raceType = getParameter("type");
   for (int i = 0; i < NUMRUNNERS; i++) {
     runners[i] = new Runner();
     if (raceType.rupareTo("unfair") == 0)
       runners[i].setPriority(i + 2);
     else
       runners[i].setPriority(2);
   }
   if (updateThread == null) {
     updateThread = new Thread(this, "Thread Race");
     updateThread.setPriority(NUMRUNNERS + 2);
   }
   addMouseListener(new MyAdapter());
   setContentPane(new AppletContentPane());
 }
 class MyAdapter extends MouseAdapter {
   public void mouseClicked(MouseEvent evt) {
     if (!updateThread.isAlive())
       updateThread.start();
     for (int i = 0; i < NUMRUNNERS; i++) {
       if (!runners[i].isAlive())
         runners[i].start();
     }
   }
 }
 public void run() {
   Thread myThread = Thread.currentThread();
   while (updateThread == myThread) {
     repaint();
     try {
       Thread.sleep(3);
     } catch (InterruptedException e) {
     }
   }
 }
 public void stop() {
   for (int i = 0; i < NUMRUNNERS; i++) {
     if (runners[i].isAlive())
       runners[i] = null;
   }
   if (updateThread.isAlive())
     updateThread = null;
 }
 class AppletContentPane extends JPanel {
   public void paintComponent(Graphics g) {
     super.paintComponent(g);
     g.setColor(Color.white);
     g.fillRect(0, 0, getSize().width, getSize().height);
     g.setColor(Color.black);
     for (int i = 0; i < NUMRUNNERS; i++) {
       int pri = runners[i].getPriority();
       g.drawString(new Integer(pri).toString(), 0, (i + 1) * SPACING);
     }
     for (int i = 0; i < NUMRUNNERS; i++) {
       g.drawLine(SPACING, (i + 1) * SPACING, SPACING
           + (runners[i].tick) / 23000, (i + 1) * SPACING);
     }
   }
 }

} class Runner extends Thread {

 public int tick = 1;
 public void run() {
   while (tick < 10000000)
     tick++;
 }

}


 </source>
   
  
 
  



URLButton -- a Button-like object that jumps to a URL

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.applet.Applet; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Label; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.URL; /**

* URLButton -- a Button-like object that jumps to a URL. MUST have an Applet
* parent since we use Applet methods.
*/

public class URLButton extends Label implements MouseListener {

 /** Applet parent, for showStatus() and showDocument(). */
 Applet parent;
 /** Text to display in label() */
 String t;
 /** URL to jump to mouseReleased mouseEnter() */
 URL u;
 /** Construct a URLButton given a URL */
 URLButton(Applet parent, String t, URL u) {
   super(t);
   this.parent = parent;
   this.t = t;
   this.u = u;
   addMouseListener(this);
 }
 /** paint() method just draws a box around us */
 public void paint(Graphics g) {
   // super.paint(graphics g);
   Dimension d = getSize();
   g.drawRect(0, 0, d.width - 1, d.height - 1);
 }
 /** When mouse enters, showStatus of URL */
 public void mouseEntered(MouseEvent e) {
   parent.showStatus(u.toExternalForm());
 }
 /** When mouse enters, clear showStatus */
 public void mouseExited(MouseEvent e) {
   parent.showStatus("");
 }
 /** When the button is pressed, go for it! */
 public void mousePressed(MouseEvent e) {
   parent.showStatus("Showing document at URL " + u);
   parent.getAppletContext().showDocument(u);
   // No error checking on showDocument() -- the
   // browser will honk at the user if the link
   // is invalid. We should open "u" ourselves,
   // check the open, and close it. Or not...
 }
 /** NotUsed */
 public void mouseClicked(MouseEvent e) {
   parent.showStatus("in mouseClicked");
 }
 /** NotUsed */
 public void mouseReleased(MouseEvent e) {
   parent.showStatus("in mouseReleased");
 }

}



 </source>
   
  
 
  



Walking Text Demo

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

//applet.html /* <TITLE>Walking Text Demo</TITLE> <BODY BGCOLOR=White> <P>Here is a walking text applet. <APPLET CODE="WalkingText" WIDTH=500 HEIGHT=70>

 <PARAM NAME=Text Value="Learning Tree International">
 <PARAM NAME=FontName Value="Helvetica">
 <PARAM NAME=FontSize Value="24">

</APPLET>


  • /

import java.applet.Applet; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; public class WalkingText extends Applet implements Runnable {

 protected String mesg = null;
 protected int xloc, yloc, width, height, textWidth, textHeight;
 protected Thread t;
 protected boolean done = false;
 /** How long to nap for each move */
 protected int napTime = 150;
 /** Applet Initializer */
 public void init() {
   xloc = 0;
   width = getSize().width;
   height = getSize().height;
   if ((mesg = getParameter("text")) == null)
     mesg = "Hello World of Java";
   String pSize = getParameter("fontsize");
   if (pSize == null)
     pSize = "12";
   String fontName = getParameter("fontName");
   if (fontName == null)
     fontName = "Helvetica";
   // System.out.println("Font is " + pSize + " point " + fontName);
   Font f = new Font(fontName, Font.PLAIN, Integer.parseInt(pSize));
   setFont(f);
   FontMetrics fm = getToolkit().getFontMetrics(f);
   textWidth = fm.stringWidth(mesg);
   textHeight = fm.getHeight();
   // System.out.println("TextWidth " + textWidth + ", ht " + textHeight);
   // use textHeight in y coordinate calculation
   yloc = height - ((height - textHeight) / 2);
 }
 /** This is important: we create a thread, so we must kill it */
 public void stop() {
   done = true;
   t = null;
 }
 /** create the thread and start it. */
 public void start() {
   if (t == null)
     t = new Thread(this);
   done = false;
   t.start();
 }
 // Usage:
 public String[][] getParameterInfo() {
   String[][] params = {
       { "text", "text", "Text to walk across the screen" },
       { "fontName", "text", "Name of font to display in" },
       { "fontsize", "int", "How big to make the text" }, };
   return params;
 }
 /** Run is called by the Thread class when there is work to do */
 public void run() {
   while (!done) {
     if ((xloc += 5) > getSize().width)
       xloc = 0;
     repaint();
     try {
       Thread.sleep(napTime);
     } catch (Exception e) {
       System.out.println("Who dares to interrupt my Sleep()? " + e);
     }
     ;
   }
 }
 /** Paint is called by Applet to redraw the screen */
 public void paint(Graphics g) {
   g.drawString(mesg, xloc, yloc);
   // if ((xloc + textWidth) > getSize().width) {
   //   int negLoc = textWidth-(width-xloc);
   //   System.out.println("xloc, textWidth, negLoc: " + xloc + "," +
   //       textWidth + ", " + negLoc);
   //   g.drawString(mesg, negLoc, yloc);
   // }
 }

}



 </source>
   
  
 
  



Your own Applet runtime environment

   <source lang="java">
 

import java.applet.Applet; import java.applet.AppletContext; import java.applet.AppletStub; import java.applet.AudioClip; import java.awt.Button; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Panel; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; public class MainClass extends Applet implements ActionListener {

 static MainClass myApplet;
 static MyStub myStub;
 Image im;
 public void init() {
   System.out.println("Code base = " + getCodeBase());
   System.out.println("Document base = " + getDocumentBase());
   System.out.println("\ninit () called");
   System.out.println("isActive () returns " + isActive());
   Button b = new Button("Visit www.jexp.ru");
   b.addActionListener(this);
   add(b);
   b = new Button("Audio");
   b.addActionListener(this);
   add(b);
   String imageName = getParameter("image");
   if (imageName != null)
     im = getImage(getCodeBase(), imageName);
 }
 public void start() {
   System.out.println("start () called");
   System.out.println("isActive () returns " + isActive());
 }
 public void paint(Graphics g) {
   if (im != null)
     g.drawImage(im, 0, 0, this);
 }
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("Audio")) {
     String soundName = getParameter("audio");
     if (soundName != null) {
       AudioClip ac = getAudioClip(getDocumentBase(), soundName);
       ac.play();
     }
     return;
   }
   try {
     URL u = new URL("http://www.jexp.ru");
     getAppletContext().showDocument(u);
   } catch (MalformedURLException exc) {
     System.out.println(e);
   }
 }
 public void stop() {
   System.out.println("stop () called");
   System.out.println("isActive () returns " + isActive());
 }
 public void destroy() {
   System.out.println("destroy () called");
   System.out.println("isActive () returns " + isActive());
 }
 public static void main(String[] args) {
   Frame frame = new Frame("AppletAndApp as an Application");
   myApplet = new MainClass();
   frame.add(new Panel().add(myApplet));
   frame.addNotify();
   myApplet.setStub(myStub = new MyStub(args));
   myApplet.init();
   frame.setSize(300, 200);
   frame.setVisible(true);
   myStub.setActive(true);
   myApplet.start();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent w) {
       myStub.setActive(false);
       myApplet.stop();
       myApplet.destroy();
       System.exit(0);
     }
   });
 }

} class MyStub implements AppletStub {

 private boolean active = false;
 private Hashtable ht = new Hashtable();
 private MyContext context;
 MyStub(String[] args) {
   context = new MyContext(); 
   if ((args.length & 1) != 0)
     return;
   for (int i = 0; i < args.length; i += 2)
     ht.put(args[i], args[i + 1]);
 }
 public boolean isActive() {
   return active;
 }
 public URL getDocumentBase() {
   URL u = null;
   try {
     u = new URL("file:/C:./x.html");
   } catch (MalformedURLException e) {
   }
   return u;
 }
 public URL getCodeBase() {
   URL u = null;
   try {
     u = new URL("file:/C:./");
   } catch (MalformedURLException e) {
   }
   return u;
 }
 public String getParameter(String name) {
   return (String) ht.get(name);
 }
 public AppletContext getAppletContext() {
   return context;
 }
 public void appletResize(int width, int height) {
 }
 public void setActive(boolean active) {
   this.active = active;
 }

} class MyContext implements AppletContext {

 public AudioClip getAudioClip(URL url) {
   return Applet.newAudioClip(url);
 }
 public Image getImage(URL url) {
   Toolkit tk = Toolkit.getDefaultToolkit();
   return tk.getImage(url);
 }
 public Applet getApplet(String name) {
   return null;
 }
 public Enumeration getApplets() {
   return null;
 }
 public void showDocument(URL url) {
   System.out.println("Showing document " + url);
 }
 public void showDocument(URL url, String frame) {
   try {
     showDocument(new URL(url.toString() + frame));
   } catch (MalformedURLException e) {
   }
 }
 public void showStatus(String message) {
   System.out.println(message);
 }
 public void setStream(String key, InputStream stream) throws IOException {
 }
 public InputStream getStream(String key) {
   return null;
 }
 public Iterator<String> getStreamKeys() {
   return null;
 }

}


 </source>