(Submitted by Jeff Breidenbach)Normal Java way: String url = new URL("http://www.digitalfocus.com"); applet.showDocument(url, "MY_NETSCAPE_FRAME"); Unfortunately, in Netscape 2 and Netscape 3 beta 4 this does not work if the user leaves the applet page - even if you have a Java frame still visible. Workaround using Netscape 3 Javascript: import netscape.javascript.*; JSObject win = JSObject.getWindow(applet); String url = new URL("http://www.digitalfocus.com"); win.eval("open(\"" + url + "\",\"" + "MY_NETSCAPE_FRAME" + "\")");
You may use
getAppletContext().showDocument(newplace);where newplace is the URL you want the browser to go to.
(Submitted by William S. Clark)
/*** Load URL.*/ public boolean loadUrl() { urlLoaded = true; // well, tried to load anyway if (url == null) return false; dbg("loadUrl()"); // use showDocument() to display new URL. // Note: Netscape 2.0b2 problems here... I don't really understand how // to catch errors from showDocument()! try { getAppletContext().showDocument(url); } catch (Exception e) { if (url.getRef() == null) { errMessage = "Couldn't load url. Try to re-start Netscape :-("; } else { errMessage = "Couldn't load url: " + url.getRef(); } return false; } return true; }
Here is the code segment that worked for me:// Open the URL and display it as a new page try { String NLinkname = "http://home.netscape.com"; URL NLink = new URL(NLinkname); MYAPPLET.getAppletContext().showDocument(NLink); } catch(java.net.MalformedURLException e) { System.out.println("Malformed URL!!!! exception"); }
There are two solution on this problem. One is as(Submitted by Bill Giel)Applet1:
import java.awt.*; import java.applet.*; public class Applet1 extends java.applet.Applet{ public boolean handleEvent(Event evt){ Applet buddy=(Applet)getAppletContext().getApplet("buddy"); return (buddy!=null) ? buddy.handleEvent(evt):false; } }Applet2:import java.awt.*; public class Applet2 extends java.applet.Applet{ String str=""; public boolean handleEvent(Event evt){ str=evt.toString(); repaint(); return true; } public void paint(Graphics g){ g.drawString(str, 0, size().height * 2 / 3); } }andtest1.html:
<html> <head>Test</head> <body> <applet code = Applet1.class width=100 height=100></applet> <applet code = Applet2.class width=400 height=30 name=buddy></applet> </body> </html>Another solution isApplet3:
import java.awt.*; import java.applet.*; class Applet2 extends Applet{ public boolean handleEvent(Event evt){ return true; } } public class Applet3 extends java.applet.Applet{ public boolean handleEvent(Event evt){ Applet2 buddy=(Applet2)getAppletContext().getApplet("buddy"); return (buddy != null) ? buddy.handleEvent(evt):false; } }and Applet2 is same above,test2.html:
<html> <head>Test</head> <body> <applet code = Applet3.class width=100 height=100></applet> <applet code = Applet2.class width=400 height=30 name=buddy></applet> </body> </html>
(Submitted by Albert M. Lopez)/* Very simple inter-applet communication demo * for any number of applets. * by Bill Giel, rvdi@usa.nai.net * http://www.nai.net/~rvdi/home.htm * * * <HTML> * <HEAD><TITLE>Inter-Applet Test</TITLE></HEAD> * <BODY> * <applet code="interapp.class" height=100 width=100></applet> * <applet code="interapp.class" height=100 width=100></applet> * <applet code="interapp.class" height=100 width=100></applet> * * </BODY> * </HTML> * * This example uses three applets of the same class, but the * technique could be applied to different applets that shared * a common class containing static members to share data among * the different applets. * */ import java.awt.*; import java.applet.*; public class interapp extends Applet implements Runnable { ///////////////////////////////////////////// // Static members are common in value to all // instances. ///////////////////////////////////////////// static final String BUTTON="Hit me!"; static String globalName = null; static boolean globalHitFlag=false; static int counter = 0; ///////////////////////////////////// // These are unique in value for each // instance. ///////////////////////////////////// String instanceName=null; boolean instanceHitFlag=false; int width,height; Thread appThread=null; public void init() { Button button; instanceName=new String("Hit on No. " + (counter + 1)); counter++; add (button=new Button(BUTTON)); width=size().width; height=size().height; button.move((width-button.size().width)/2, (width-button.size().width)/2); } public boolean action(Event evt, Object arg) { if(arg.equals(BUTTON)){ globalName=instanceName; globalHitFlag=!globalHitFlag; return true; } else return false; } public void paint(Graphics g) { if(null != globalName){ FontMetrics fm=g.getFontMetrics(); int yPos=height/2; int xPos=(width-fm.stringWidth(globalName))/2; g.drawString( globalName,xPos,yPos); } } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); for(;;) //////////////////////////////////////// // If the instance data no longer equals // the global data, then there was a hit. ///////////////////////////////////////// if(instanceHitFlag != globalHitFlag){ repaint(); instanceHitFlag=globalHitFlag; } } public void start() { if(appThread == null){ appThread = new Thread(this); appThread.start(); } } public void stop() { appThread.stop(); appThread=null; } }
In this example, Applet1 gets text from an textBox and then calls the appendText function of Applet2. Applet2 appends the text to a textArea box.(Submitted by Matt Young)// Applet1 import java.awt.*; public class Applet1 extends java.applet.Applet { TextField inputText; Panel myPanel; public void init() { resize( 100, 100 ); setLayout(new BorderLayout()); add("South", myPanel = new Panel() ); GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints con = new GridBagConstraints(); myPanel.setLayout( gridBag ); inputText = new TextField( "", 15 ); inputText.setEditable( true ); con.gridwidth = GridBagConstraints.REMAINDER; // end of row gridBag.setConstraints( inputText, con ); // end of row myPanel.add( inputText ); con.gridwidth = 1; Button enterText = new Button( "Enter Text" ); myPanel.add ( enterText ); myPanel.enable(); } public boolean action(Event ev, Object arg) { if( ev.target instanceof Button) { String textMsg = inputText.getText().trim(); Applet2 applet2 = (Applet2)getAppletContext().getApplet("applet2"); if ( applet2 != null ) { applet2.AppendText( textMsg ); return true; } else return false; } return false; } //Applet2 import java.awt.*; public class Applet2 extends java.applet.Applet { TextArea textBox; Panel myPanel; public void init() { resize ( 100, 100 ); setLayout(new BorderLayout()); add("South", myPanel = new Panel() ); textBox = new TextArea( 5, 40 ); myPanel.add( textBox ); myPanel.enable(); } public void AppendText( String msg ) { String newLine = new String( "\n" ); textBox.appendText( msg ); textBox.appendText( newLine ); } }
From Lemay & Perkins, p. 298:(Submitted by Friedhelm Ries)
for( Enumeration e = getAppletContext().getApplets(); e.hasMoreElements();) { Applet current = (Applet)(e.nextElement()); f(current); }where f is a function call.
Quoting elharo@sunsite.unc.edu (in his comp.lang.java.faq) http://sunsite.unc.edu/javafaq/javafaq.html:"At this point in time applets may communicate with other applets on the same page. As yet there is no way for applets on different pages to communicate directly. This may be added at some point in the future."For applets on the same page Arthur van Hoff has provided this example:
Applet 1: import java.awt.*; public class Applet1 extends java.applet.Applet { public boolean handleEvent(Event evt) { Applet2 buddy = (Applet2)getAppletContext().getApplet("buddy"); return (buddy != null) ? buddy.handleEvent(evt) : false; } } Applet 2: import java.awt.*; public class Applet2 extends java.applet.Applet { String str = ""; public boolean handleEvent(Event evt) { str = evt.toString(); repaint(); return true; } public void paint(Graphics g) { g.drawString(str, 0, size().height * 2 / 3); } } HTML: <HTML> <HEAD> </HEAD> <BODY> <applet code=Applet1.class width=100 height=100></applet> <applet code=Applet2.class width=400 height=30 name=buddy></applet> </BODY> </HTML>It is conceivable to have applets that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial. However there is currently no secure way to store this data on the client.
/* code snippet to grab a page from the httpd server * and parse the returned info. */ ... /* build the URL */ String tmpURL = new String("http://www.foo.bar/junk.html"); URL infoLink = new URL(tmpURL); /* start the connection with the httpd and talk */ InputStream serverIO = infoLink.openStream(); /* the stream doesn't need to be buffered, but * it's what I used during testing */ BufferedInputStream bufServerIO = new BufferedInputStream(serverIO); /* init the buffer that'll hold the info coming from the server */ StringBuffer oneLink = new StringBuffer(); /* setup some parsing variables */ int info; char histchar1=' ',histchar2=' '; /* do the deed - one character at a time. * you can use read(byte b[], int off, int len) if you know * how many characters you expect from the server. */ while((info=bufServerIO.read())!=-1) { oneLink.append((char)info); /* make note of the info */ /* Sample Parsing: Now I look for the "/UL" string * parsing this way is ALOT faster than using oneLink.toString().indexOf("/UL") */ if(((char)info=='L')&&(histchar1=='U')&& (histchar2=='/')) { /* do stuff with oneLink */ } histchar2=histchar1; histchar1=(char)info; } ...
// The following class would run as an application/applet. Use the // supplied HTML file to run as an applet.import java.awt.*; import java.applet.*; public class easyOne extends Applet { public void init() { } public void resize() { resize(300,300); } public easyOne() { setLayout(new BorderLayout()); Panel p1 = new Panel(); p1.setLayout(new FlowLayout()); add("South", p1); p1.add(new Button("ButtonOne")); p1.add(new Button("AnotherButton")); } public void paint(Graphics g) { g.setColor(Color.cyan); g.drawRect(10,10,150,150); g.fillRect(10,10,150,150); } public static void main(String args[]) { Frame f1 = new Frame("Standalone Application"); easyOne s1 = new easyOne(); f1.add("Center", s1); f1.resize(300, 300); f1.show(); s1.init(); s1.start(); } }
The way to point to java applets which are located on a different server is to use the "CODEBASE" parameter in the applet html. It seems you cannot explicitly list the URL of the java applet in the CODE parameter but you CAN list a URL in the CODEBASE parameter. So....applet code="MyJavaApplet.class" width = 300 height = 300 CODEBASE="http://www.mydomain.fun/appletdirectory/"is the correct html syntax to go to a different server (the one listed on the CODEBASE parameter) and get the applet listed on the CODE parameter.
String myHTML = new String( "javascript:'<title>My Page</title><h1>My Page</h1>'"); getAppletContext().showDocument(new URL(myHTML));
When your browser moves on to a different page, it will generally call your applet's stop() method. If you override the default, you can keep your applet running "in the background" while Netscape does other things. Adding the following to your class will probably do what you want:public void stop() { return; }As you can see, the stop() method doesn't actually do anything. It just overrides the default so that Netscape (or whatever) can't use it to stop your applet.This method is especially useful if your applet floats in it's own frame. Note that this means you must provide your users with some other way to kill off your applet. Also note that if your applet displays inline (ie. not in it's own frame), and the user goes off and does other stuff with Netscape, your applet will still be running, taking valuable CPU time.
Be careful overriding the stop() method.
Use Applet.getAppletContext(), Applet.getCodeBase(), and Applet.getDocumentBase().
How do I get the current location of the browser? the current HTML content? the Bookmarks the user saved? the Go list? the current browser font?
The best way to do this is on the server, with a CGI script. For instance:(Submitted by Cliff Berg)#!/usr/local/bin/perl use CGI; # CGI.pm See note below $cgi = new CGI; if(scalar(grep(/Macintosh/, $ENV{HTTP_USER_AGENT})) > 0) { # Give them the no applet page print $cgi->redirect('no-applet.html'); } else { # Give them the applet page print $cgi->redirect('applet.html'); } exit(0);This is assuming you have perl and the CGI.pm module by Lincoln Stein. If you do not, get perl at: ftp://ftp.netlabs.com/pub/outgoing/perl5.0/ and get CGI.pm at: http://www-genome.wi.mit.edu/ftp/pub/software/WWW/.
Any HTML that appears between the applet tag and the end-applet tag is executed if the browser does not support applets. Thus, this non-Java HTML can provide whatever content is intended for a non-Java browser. The applet can, on the other hand, immediately do a getAppletContext().showDocument(url), causing the browser to go to another page without delay.
Adapted from Netscape's own Javascript help files:<APPLET CODE="colors.class" WIDTH=1000 HEIGHT=60 NAME="colorApp" MAYSCRIPT> </APPLET> <FORM NAME=colorText> <INPUT TYPE="text" NAME="textBox" LENGTH=50> <INPUT TYPE="button" VALUE="Change Text" onClick="document.colorApp.setString(document.colorText.textBox.value)"> <P><INPUT TYPE="button" VALUE="Restart" onClick="document.colorApp.start()"> </FORM>
You want to create the second frame with a name. ie:<frame name="control" src="applet.html" > <frame name=applet frame target" src="" >Then you would use the following code:void moveFrame(String dest) { URL destURL=null; try { destURL = new URL(dest); } catch (MalformedURLException mal){ } getAppletContext().showDocument(destURL,"target"); }
In the applet tag, set height=0 width=0.Here is an example that puts scrolling text in the status bar but doesn't draw anything on the page itself. This works (netscape 2.0 Solaris 2.4) but isn't very pretty.
/* ScrollStatus.java emacs C++ mode: -*- C++ -*- Optional parameters: message, width Default values: message = " Isn't scrolling text in the status line annoying? " width = 36 Example usage: <applet codebase=ScrollStatus code=ScrollStatus.class width=0 height=0> <param name="message" value="Hello World!"> <param name="width" value="24"> </applet> */ import java.util.*; import java.applet.Applet; public class ScrollStatus extends Applet implements Runnable { Thread thread; String message; StringBuffer buffer; int at; int width; public void init(){ message = getParameter("message"); if(message == null) message = " Isn't scrolling text in the status line annoying? "; String ws = getParameter("width"); if(ws == null) width = 36; else{ width = Integer.valueOf(ws).intValue(); } if(width < 5 || width > 180) width = 36; buffer = new StringBuffer(width); buffer.setLength(width); at = 0; if(message.length() < width){ char buf[] = new char[width]; for(int i = 0; i < width; ++i) buf[i] = ' '; message.getChars(0, message.length(), buf, (width - message.length()) / 2); message = new String(buf); } } public void start(){ thread = new Thread(this); thread.start(); } public void stop(){ thread.stop(); } public void scroll(){ int l = message.length(); int k = at; for(int i = 0; i < width; ++i, ++k){ if(k >= l) k = 0; buffer.setCharAt(i, message.charAt(k)); } getAppletContext().showStatus(buffer.toString()); at++; if(at >= l) at = 0; /* This seems to work just as well (or poorly :(. I thought that it might be creating a lot of strings for the GC to clean up though. the "buffer" and "at" variable are not needed for this code. String msg = message.substring(0, width-1); getAppletContext().showStatus(msg); msg = message.substring(1); message = msg + message.charAt(0); */ } public void run(){ while(true){ scroll(); try{ Thread.sleep(25); // wait 25 ms } catch(InterruptedException e){ break; } } } }
Try http://www.apc.net/neva/java/ for a DDE server implemented using native methods. Not ideal but I think its probably the only way.
"For example, I would like a scrolling banner in one frame to announce the content that is displayed in another frame."
Have the html page with the applet in the same directory. The browser will prompt the user for the username/password when they request the page and then remember it when it needs the graphics.See also, "How do I retrieve an html page which is on an http server using authentication?" in the section,
(Editor's note: We do not recommend that programmers use this technique.)Here is how the no warning thing works, at least as I do it:
First, set some flag to indicate that the thing isn't shown yet.
In init():
In run() or handleEvent(): make a call to repaint()
- make a Frame but don't .show() it.
- Make a window on that frame, and reshape it as you please.
- .show() the window, and add "this" to it(dont use this.show() yet.
- reshape "this" to something equal or greater in size than the window.
In paint():
There are a number of variations on the theme, it really doesn't matter what order you do some of the steps in. The point is, don't do this.show() until after the window is shown, and do it outside of init a call from handle event to repaint in the case of WINDOW_EXPOSE works.
- check the flag you set.
- if true, do a this.show() and set the flag as false.
If you try to reshape the window, the string will reappear unless you hide "this", reshape the window, then show "this" again.
If the applet stops running, the warning string will generally reappear.
- Matt Durham, Feb. 13, 1997
Here is the code:
import java.awt.*; public class nowarn extends java.applet.Applet implements Runnable{ Frame framey; Window winny; Thread runny; boolean startflag=true; public void init(){ setBackground(Color.black); framey=new Frame(); winny=new Window(framey); winny.show(); this.resize(500,300); winny.add(this); this.move(0,0); start(); }//end init public void start(){ if(runny==null){ runny=new Thread(this); runny.start(); } run(); }//end start public void stop(){ if(runny!=null){ runny.stop(); runny=null; } }//end stop public void update(Graphics g){ paint(g); }//end update public void paint(Graphics g){ if(startflag){ winny.reshape(20,20,300,300); this.show(); startflag=false; }//endif: first time through only }//end paint public void run(){ while(true){ repaint(); try{runny.sleep(100);} catch(InterruptedException e){} } }//end run }//end nowarnHTML:
<html> <head> <title> Look, no warning... </title> </head> <body bgcolor="#FFFFFF"> <applet code="nowarn.class"></applet> </body>