Необходим ли какой-то специальный серверный софт для использования апплетов?

Нет. Java апплеты могут быть размещены на любом HTTP сервере. На стороне сервера они
обрабатываются как любые другие файлы, такие как текст, картинки или звуковые файлы.
Апплет обрабатывается уже на клиентской стороне с помощью включенной в браузер Java технологией.

Как передать сообщение от одного апплета другому?

В этом примере, FirstApplet кодирует сообщение для SecondApplet в поисковой секции SecondApplet.html URL.
Затем, SecondApplet декодирует поисковую секцию его URL и достает сообщение, пришедшее от FirstApplet.



FirstAppletJ.html



<HTML><HEAD></HEAD><BODY>

<APPLET CODE="FirstAppletJ.class" 

        HEIGHT=100 

        WIDTH=300>

</APPLET></BODY></HTML>



FirstAppletJ.java



import java.applet.*;    

import java.awt.*;

import java.awt.event.*;

import java.net.*;



public class FirstAppletJ extends Applet implements

    ActionListener {

 Button b;

 TextField t;

 public void init() {

  add(new Label("Message to 2nd applet :"));

  add(t= new TextField(20));

  add(b = new Button("Load 2nd applet"));

  b.addActionListener(this);

  }



 public void actionPerformed(ActionEvent ae) {

  if (ae.getSource() == b) {

    try {

     getAppletContext().showDocument

       (new URL(getCodeBase()

         "SecondAppletJ.html?" "message=" + URLEncoder.encode(t.getText())));

     }

    catch (Exception e) {

     e.printStackTrace();

     }

    

   }

 }



SecondAppletJ.html



<HTML><HEAD></HEAD><BODY>

<APPLET CODE="SecondAppletJ.class" 

        HEIGHT=100 

        WIDTH=400>

</APPLET></BODY></HTML>



SecondApplet.java



import java.applet.*;

import java.awt.*;

import java.net.*;



public class SecondAppletJ extends Applet {

 public void init() {

   Label l = new Label("Message from 1st Applet");

   add (l);

   TextField tf = new TextField50 );

   add(tf);

   

   // complete current URL

   String s = getDocumentBase().toString();

   

   // extract the search (or query) section

   String theMessage = s.substring(s.indexOf('?'1);



   // remove message header

   theMessage = theMessage.substring("message=".length());



   // decode the string (incomplete)

   theMessage = theMessage.replace('+',' ');



   /* with JDK1.2, the decoding can be done with java.net.URLDecoder.decode(theMessage).

   

      you to convert from a MIME format called "x-www-form-urlencoded" to a String

      To convert to a String, each character is examined in turn:

      . The ASCII characters 'a' through 'z',

        'A' through 'Z', and '0'

        through '9' remain the same.

      . The plus sign '+'is converted into a

        space character ' '.

      . The remaining characters are represented by 3-character

        strings which begin with the percent sign,

        "%xy", where xy is the two-digit hexadecimal 

        representation of the lower 8-bits of the character.

   */





   

   tf.setText(theMessage);

   }

 }

Как избавиться от мерцания в апплете?

Обычно для этой цели используют двойную буферизацию. Но это не решает проблему на 100%.
Следующие трюки могут быть использованы для решения проблемы мерцания в анимации:

  1. Use Media Tracker for downloading the images.
  2. Use double buffering.
  3. Change the default background color of the applet to the color of you Canvas by using setBackground(Color of the Canvas) in the init method of the applet.
  4. In an animation if you are updating only part of a area use repaint(x1,y2,x2,y2) instead of repaint().

Как получить доступ к параметрам, переданным через URL?

Этот пример показывает, как получить параметры, переданные через URL.



import java.applet.*;

import java.util.*;

public class SimpleApplet extends Applet {

 Hashtable searchparms;

 public void init() {

  // dump to the console the URL, the search and search values

  //  the URL  http://myserver.com/mypage.html?value1=x&value2=y&value3=z

  //  the search  value1=x&value2=y&value3=z

  //  the values  value1=x

  //              value2=y

  //              value3=z

  //

  // then the values are stored in a Hashtable for easy reference.

  // ex. String name = searchparms.get("value2")

  doit();

  }



 public void doit() {

  int i;

  String completeURL = getDocumentBase().toString();

  System.out.println("Complete URL: " + completeURL);

  i = completeURL.indexOf("?");

  if (i > -1) {

   String searchURL = completeURL.substring(completeURL.indexOf("?"1);

   System.out.println("Search URL: " + searchURL);



   StringTokenizer st =

     new StringTokenizer(searchURL, "&");

   while(st.hasMoreTokens()){

    String searchValue=st.nextToken();

    System.out.println("value :" + searchValue);

    }

   initHashtable(searchURL);

   dumpHashtable();

   }

  }



  public void initHashtable(String search) {

   searchparms = new Hashtable();

   StringTokenizer st1 =

     new StringTokenizer(search, "&");

   while(st1.hasMoreTokens()){

     StringTokenizer st2 =

       new StringTokenizer(st1.nextToken()"=");

     searchparms.put(st2.nextToken(), st2.nextToken());

     }

   }



  public void dumpHashtable() {

    Enumeration keys = searchparms.keys();

    System.out.println("--------");

    whilekeys.hasMoreElements() ) {

      String s = (Stringkeys.nextElement();

      System.out.println("key : " + s + " value : " + searchparms.get(s));

      }

    System.out.println("--------");

    }

 }

Как узнать хост, откуда загружен апплет?

Вы можете узнать хост, откуда загружен апплет с помощью метода getCodeBase().

Пример демонстрирует простой способ защиты от копирования. Если полученный codebase не совпадает с предустановленным хостом, то можно завершать приложение.



import java.applet.*;



public class MyApplet extends Applet {

  public void init() {

    System.out.println(getCodeBase());

    //

    // you can check the value of getCodeBase()

    // to implements a simple copy protection

    // scheme. If it's not equals to your

    // URL then quit.

    //

    }

  }

Страница 3 из 3«123