Is it possible to change the contents of the applet from html page where it is embedded I have a network diagram. I have to change the contents of applet, depending on where the user clicks on the diagram. Thanks Raji
Rob Hunter
Ranch Hand
Joined: Apr 09, 2002
Posts: 788
posted
0
Im new at this but by "changing the contents of the applet" do you mean insert a different applet in it's place or just change variable(s) values? I would guess by using Javascript and accessing the applet array for the page you could do just about anything you want. I mainly program in VB, Perl, etc.., and have only recently started looking at Java so I hope my answers and questions in here arent dumb.
Darren Hicks
Greenhorn
Joined: Jul 31, 2001
Posts: 6
posted
0
Yes, you can have HTML (via Javascript ) communicate with an Applet. Here are the basics: 1) Define a public method in your Applet that other script can access ( I used setMessage ) 2) Define a Javascript function to delegate a call to the Applet, accessing the applet via document.applets['TestHtmlCommApplet']. 3) Call the javascript in the appropriate places ( and with parameters, if necessary ). I'm calling it from the onclick event of a button. Here's code that will work, so long as the .java is compiled and in the same directory as the html. ---------------- TestHtmlCommApplet.java -------- import javax.swing.*; public class TestHtmlCommApplet extends JApplet { private Stringmsg; public void init() {} public void setMessage( String disp ) { msg = disp; getContentPane().setVisible( false ); getContentPane().removeAll(); getContentPane().add( new JLabel( disp, JLabel.CENTER ) ); getContentPane().setVisible( true ); } } ------------------------------------------------- ----------- TestHtmlCommApplet.html ------------- <html> <head> <title>HTML/Applet Test</title> <script language="JavaScript1.2"> // changeDisplay will dispatch a call to the Java Applet function changeDisplay( ) { // The applet has a method called setMessage document.applets['TestHtmlCommApplet'].setMessage( document.forms[0].display.value ); } </script> </head> <body bgcolor=#C0C0C0 topmargin="2" leftmargin="2" bottommargin="2" rightmargin="2" > <center> <H1>HTML Communicating to an Applet</H1> <applet codebase="." applet code="TestHtmlCommApplet" name="TestHtmlCommApplet" width=300 height=100> </applet> <FORM> <INPUT TYPE=TEXT NAME=display VALUE="Show in applet..."><BR> <INPUT TYPE=BUTTON VALUE="Send Text To Applet" nclick="changeDisplay();"> </FORM> </center> </body> </html> ------------------------------------------------ Sorry if the formatting translates poorly to the message board ( NOTE: I could not post with "onclick" in HTML above, change "nclick" to "onclick"! ) You can go the other direction, from Applet to Javascript on an HTML page by including the MAYSCRIPT tag in your HTML <Applet> tag.