• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 328
  • Last Modified:

static variable not working(very urgent)

the following is the code which is not working

public class f1 extends java.applet.Applet{
static String s1;
public void init(){
s1="hello";
try{
getAppletContext().showDocument(new URL("file://c:/.../f2.html"));
}
catch(MalformedURLException ex1)
{}
}
}

public class f2 extends java.applet.Applet{
f1 f=new f1();
public void init(){
System.out.println(f.s1);
}
}

i have tried all the possibilities but it print null values.
some of the possibilities are
1.i used static method but it didn't work
before init method.
like
static{
f1 f=new f1();
System.out.println(f.s1);
}

2.the same code i wrote in run method then also it didn't work.

there no possible error in syntax.
please send me some good solutions.

waiting for reply
0
s_venkat_s
Asked:
s_venkat_s
  • 10
  • 9
  • 4
  • +1
1 Solution
 
Ravindra76Commented:
Hi s_venkat_s,

  Inter-applet communiaction won't work lime this. You can not create an instance of applet directly in another class.

Inter-applet communication will work if they are loaded from same page.

Instead of creating directly f1,

use the function
getAppletContext().getApplet("f1")

by giving name=f1 in applet tag in html file which f1.java applet embedded.

Try with this,

BEst of luck
0
 
Ravindra76Commented:
Hi,

I am posting Useful inforation in perviously asked question of this site:



Full details are here:

http://www.netwave.net/members/raji/sb/iactop.htm

Shows how to transfer data between two applets with a working
example here:

http://www.netwave.net/members/raji/sb/iacapplet.htm

Uses three applets. Source, target and middle class to communicate
between them.

The middle class is used for a specific reason as explained on the
pages above...though you can do it without it.

Use this html:



<html>

<head>
<meta name="GENERATOR" content="Microsoft FrontPage 3.0">
<title>IAC Applet page</title>
</head>

<frameset framespacing="0" border="false" frameborder="0"
cols="*,*">
<frame name="left" src="iacmain.htm" scrolling="auto">
<frame name="right" src="subframe.htm" scrolling="auto">
<noframes>
<body>
<p>This page uses frames, but your browser doesn't support
them.</p>
</body>
</noframes>
</frameset>
</html>




and compile these three applets:



*
* Applet
* Author: D.L.Sivakumar
* Date: 16 Nov. 1997
*
* This source code is published in the internet for education
* purpose only. Author shall not be liable any damages suffered
* by user as a result of using, modifying or distributing
* this source code.
*
* Function: This applet is a Source Applet in Inter-Applet
Communication.
* It uses MiddleGuy class to set the value into a static variable
* which is read by the Target Applet.
*/


import java.awt.*;
import java.applet.*;
import java.net.*;
import MiddleGuy;



public class MainApp extends Applet
{
void button1_Clicked(Event event)
{
try
{
MiddleGuy.setTextData(txtName.getText());
AppletContext ac = getAppletContext();
URL u = new URL(getDocumentBase(), "subframe.htm");
ac.showDocument(u, "right");
}
catch(MalformedURLException e)
{
showStatus("Error " + e);
}
}


public void init()
{
super.init();
setLayout(null);
addNotify();
resize(435,239);
button1 = new java.awt.Button("Send Text to Target
Applet");
button1.reshape(120,168,236,32);
add(button1);
txtName = new java.awt.TextField(25);
txtName.reshape(168,84,157,24);
add(txtName);
lblName = new java.awt.Label("Enter Text");
lblName.reshape(60,84,79,23);
add(lblName);
label1 = new java.awt.Label("Source Applet",Label.CENTER);
label1.reshape(48,12,367,37);
label1.setFont(new Font("Dialog", Font.BOLD, 16));
add(label1);

}

public boolean handleEvent(Event event)
{
if (event.target == button1 && event.id ==
Event.ACTION_EVENT) {
button1_Clicked(event);
return true;
}
return super.handleEvent(event);
}


java.awt.Button button1;
java.awt.TextField txtName;
java.awt.Label lblName;
java.awt.Label label1;

}



*
* Applet
* Author: D.L.Sivakumar
* Date: 16 Nov. 1997
*
* This source code is published in the internet for education
* purpose only. Author shall not be liable any damages suffered
* by user as a result of using, modifying or distributing
* this source code.
*
* Function: This applet is a Target Applet in Inter-Applet
Communication.
* It uses MiddleGuy class to get the value from the static variable
* which is set by the Source Applet.
*/

import java.awt.*;
import java.applet.*;
import MiddleGuy;

public class SubApp extends Applet {

public void init() {
super.init();



setLayout(null);
addNotify();
resize(426,266);
lbl_sname = new java.awt.Label("Target Field");
lbl_sname.reshape(48,120,110,23);
add(lbl_sname);
txt_sname = new java.awt.TextField(20);
txt_sname.setEditable(false);
txt_sname.reshape(180,120,200,25);
add(txt_sname);
label1 = new java.awt.Label("Target Applet",Label.CENTER);
label1.reshape(36,24,367,37);
label1.setFont(new Font("Dialog", Font.BOLD, 16));
add(label1);

/* Call to the Middle Guy class method directly as this method is
defined as static method. */
txt_sname.setText(MiddleGuy.getTextData());

}


public boolean handleEvent(Event event) {
return super.handleEvent(event);
}



java.awt.Label lbl_sname;
java.awt.TextField txt_sname;
java.awt.Label label1;

}


*
* Applet
* Author: D.L.Sivakumar
* Date: 16 Nov. 1997
*
* This source code is published in the internet for education
* purpose only. Author shall not be liable any damages suffered
* by user as a result of using, modifying or distributing
* this source code.
*
* Function: This is a Middle class used in Inter-Applet
Communication.
* It uses aa static variable which is used by the Source and the
* Target Applet.
*/


public class MiddleGuy
{

public static void setTextData(String str)
{
txt = str;
}

public static String getTextData()
{
return txt;
}

static String txt;

}

0
 
heyhey_Commented:
replace
  f1 f=new f1();

with
  f1 f=new f1();
  f.init(); // this method initializes the static variable
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
heyhey_Commented:
> You can not create an instance of
> applet directly in another class.

You can.
applets are standard Java objects - you can always create Applet objects, call methods on them etc.

0
 
Ravindra76Commented:
Hi heyhey,

 I have a small doubt.

 Is it posible for calling constructor of applet eventhough it is not in same page?

Why to use getAppletContext()?

Thank you
0
 
heyhey_Commented:
'normal' applets have lifecylce that is managed from the applet-viewer ( browser) - it creates them, gives them some screen resources and destroys them. it allows 'normal' applets to communicate with other 'normal' applets created from the same applet-viewer.

but of course you can create applet object, show them on the screen and destroy them yourself.

the code that s_venkat_s  has posted has nothing to do with applets - the problem is coming from mixing some static and non-static methods ...
0
 
Ravindra76Commented:
Hi heyhey,

 Now i think that my above code is useless. Is it true.

 If not, i want just to know when it will be useful.

Thank you
0
 
Ravindra76Commented:
Hi heyhey,

will it work

f1 f=new f1();
System.out.println(f.s1);
 
  or

f1 f=new f1();
System.out.println(f1.s1);

since s1 is a static variable

Thank you
0
 
heyhey_Commented:
your code is example for interapplet communication - how to exchange infomation between several applets located on the same web page.

the original code (and question) does not concern applets communication at all (in my opinion) - it can be easily rewritten

public class f1
{
 static String s1;
 public void init()
 {
   s1="hello";
   try
   {
    ContextManager.getSomeAppletContext().showDocument(new URL("file://c:/.../f2.html"));
   }
   catch(MalformedURLException ex1)
   {}
 }
}

public class f2 extends java.applet.Applet
{
  f1 f=new f1();
  public void init()
  {
    System.out.println(f.s1);
  }
}
0
 
Ravindra76Commented:
Thank you very much heyhey.
0
 
heyhey_Commented:
'
will it work
f1 f=new f1();
System.out.println(f.s1);
  or
f1 f=new f1();
System.out.println(f1.s1); '

both of them will work (compile) fine.

you can use directly
System.out.println(f1.s1);
or
System.out.println((new f1()).s1);



0
 
heyhey_Commented:
ok

friends ? :)
0
 
Ravindra76Commented:

Ok.

One small doubt.

So many are using your :) symbol and when asked heyhey knows only.

What is the meaning 0f
:) or :-) or :)-
0
 
heyhey_Commented:
:-) is a smile.

slant your head to the left and examine that sign. :)

just a link
http://ourworld.compuserve.com/homepages/laszlo_gabris/Smiley.txt
0
 
JodCommented:
looks like one of my previous inter applet examples?

My copyright lawyer is formulating a letter as we speak...;-)

The example you've given is really for more general inter applet communication. Not neccessarily needed here, as it there is a simpler way to approach the problem. the coide above is more useful when you have applets in different frames that wish to talk to each other and such like, but there are limitations on when and how you can use it.

Maybe I'm missing some thing here, but can't you just do:

public class f1 extends java.applet.Applet {
  static String s1 = "hello";

  public void init(){
    try{
      getAppletContext().showDocument(new URL("file://c:/.../f2.html"));
    } catch(MalformedURLException ex1) {}
  }
}

public class f2 extends java.applet.Applet {
  public void init(){
    System.out.println(f1.s1);
  }
}

0
 
Ravindra76Commented:
Hi Jod,

That's why i told at the begining of the example that it was not mine.

>>

I am posting Useful inforation in perviously asked question of this site:

And i did not propose as answer.
Just a comment. Other wise i will propose as answer.

It is just to reduce the time.
If you did n't come to this question, and if he needs this, then my comment of your pervious answer is useful to him.

Thank you
0
 
s_venkat_sAuthor Commented:
from s_venkat_s.

to ravindra76,
i even tried the communication as you said .
<applet name="name" code="f1.class" width=...height=..>
</applet>


secound file
Applet a1=getAppletContext().getApplet('name");

it also did not work.

do you have any other suggestions for static variables.
it worked well in jdk1.1.5 but gave null values in jdk1.2.

0
 
Ravindra76Commented:
Hi s_venkat_s,

 Try with heyhey solution whcih is perfectly suitable to your application than mine ( Upcourse JODs ).

And I have jdk118 only in my system

Best of lcuk
0
 
JodCommented:
just smile ravindra...:-)

As always, I'm only joking.
0
 
heyhey_Commented:
>> As always, I'm only joking.

hmm ... , some of your code looks quite 'serious' :)
0
 
Ravindra76Commented:

Hi Jod,

 I think it is real and posted a question EE about copy rights
0
 
JodCommented:
Oh yeah - I see...sorry about that. I forget the dry english sense of humour sometimes does not translate well.


Back to the above problem, I have another example which explains the plot slightly better.

It's a big example, but explains the problem well:


QUESTION:

I have two applets running on the same page, one in each of two frames. I want them to communicate, but when I do a getAppletContext.getApplet() call, the second applet can't find the first. I've gone through the enumeration returned by getApplets(), and only the applet that makes the call is found.

Is there a special syntax I have to use to find an applet running in another frame?

ANSWER:

First a little background for newcomers:

For security reasons, there are many restrictions on the ability of an applet to communicate with other processes. However, an applet can communicate with other applets running on the same Web page. How is this done?

One way is to give names to each applet on a Web page using a NAME specifier in the applet tag. Here's a sample HTML file containing two applets named "senderapplet" and "receiverapplet." Note that the names MUST be in lowercase letters:


**********************************

<HTML>

<HEAD>
<TITLE> Test </TITLE>
</HEAD>

<BODY>

    <P>
        This applet sends outputs
        to the applet below.
    </P>

    <APPLET CODE="Sender.class" WIDTH=290 HEIGHT=150 NAME="senderapplet">
       This browser can't run applets.
    </APPLET>

    <P>
        This applet receives inputs
        from the applet above.
    </P>

    <APPLET CODE="Receiver.class" WIDTH=290 HEIGHT=150 NAME="receiverapplet">
       This browser can't run applets.
    </APPLET>


</BODY>

</HTML>

**********************************
Information about the Web page containing an applet is represented in an AppletContext object, which an applet can obtain using its getAppletContext method:
AppletContext context = getAppletContext();
Among other things, this context contains references to all other applets on the Web page. These references can be accessed from the applet's name (given by the NAME specifier above) using the getApplet method. For example, if an instance of Sender.class wants a reference to the instance of the Receiver.class residing on the same Web page, it can call:
Applet recApp = context.getApplet("receiverapplet");
Communication with the Receiver applet is possible if the Receiver applet provides a special public method that can process messages. Assume the Receiver object has a method called ProcessInput, which expects a String input. Then the Sender object can invoke this method through the reference obtained above (after the appropriate cast):
((Receiver)recApp).processInput("your message here");
Now the problem:
A frame is an HTML element that contains a Web page. Thus, using frames it is possible to nest Web pages. Although not yet a standard HTML feature, frames are supported by Netscape. Assume the Sender and Receiver applets above reside in separate HTML files called "send.html" and "rec.html," respectively. Using the frame feature, they can appear in separate frames on the same Web page:


**********************************

<HTML>

  <HEAD>
  <TITLE> Parent Frame </TITLE>
  </HEAD>
   
  <FRAMESET COLS="50%, 50%">

    <FRAME NAME="sender"
           SRC="send.html"
           MARGINHEIGHT=2
           MARGINWIDTH=2
           SCROLLING="no"
           NORESIZE>

    <FRAME NAME="receiver"
           SRC="rec.html"
           MARGINHEIGHT=2
           MARGINWIDTH=2
           SCROLLING="no"
           NORESIZE>

  </FRAMESET>

</HTML>

**********************************
Unfortunately, the AppletContext of the Sender applet represents send.html, the Web page within the Sender frame. Since the Receiver applet resides in rec.html, it will not be among the applets represented inside the Sender applet's AppletContext. Thus, the technique outlined above fails.
And now the solution:

I wish I could take all the credit for this idea, but alas, I stand on the shoulders of giants. My inspiration was a "Tip of the Week" submitted to JavaWorld by Greg Williams.

My strategy is this: Since Sender's AppletContext doesn't hold a reference to the Receiver applet, why not create our own class and call it a MetaContext, containing references to all registered applets? Receiver and Sender applets can register themselves with the MetaContext during initialization. The MetaContext can provide its own getApplet method to allow applets to access registered applets.

But how will applets running on different pages obtain references to a common MetaContext? This should be possible if everything in the MetaContext is static.

Here's my definition of MetaContext. Registered applets are held in a hash table, where they are indexed by their names:


**********************************

import java.applet.*;
import java.util.*;

public class MetaContext
       {
     // registered applets live here
     private static Hashtable applets = new Hashtable(10);

     // to access registered applets
     public static Applet getApplet(String s) {
        return (Applet)applets.get(s);
      }

     // to register applets
     public static void regApplet(String s, Applet a) {
        applets.put(s, a);
     }

   // etc.
}

**********************************

As an example, my Sender and Receiver applets each contain two TextFields, one showing the applet's input, the other showing its output. The user enters a number x into the Sender's input field, x is sent to the Receiver, x appears in the Receiver's input field, the Receiver computes y = x * x, places y in its output field, then sends y back to the Sender. The Sender computes z = y + 1, then displays z in its output field. The example is silly, but it does show a non-trivial, two-way communication between Sender and Receiver.
To receive inputs, both Sender and Receiver provide a method:

public void processInput(String s) { ... }
To access the Receiver's processInput() method, the Sender first obtains a reference to the Receiver applet through the MetaContext:
Applet recApp = MetaContext.getApplet("receiverapplet");
Then invokes the Receiver's processInput method:
((Receiver)recApp).processInput(sendField.getText());
Here's the complete code for Sender and Receiver:
**********************************

// Sender.java

import java.awt.*;
import java.applet.*;

public class Sender extends Applet {

   private TextField sendField;    // input field
   private TextField receiveField; // output field

   public void init() {
      setLayout(new FlowLayout());
      sendField = new TextField("SEND", 7);
      add(sendField);
      receiveField = new TextField("RECEIVE", 7);
      add(receiveField);
      // register with MetaContext
      MetaContext.regApplet("senderapplet", this);
   }

   public boolean action (Event e, Object arg) {

      if (e.target instanceof TextField && e.target == sendField) {

         AppletContext context = getAppletContext();
         context.showStatus("***** " + sendField.getText() + " sent!");

         // get reference to receiver applet:
         // Applet recApp = context.getApplet("receiverapplet");
         Applet recApp = MetaContext.getApplet("receiverapplet");

         // send message to receiver applet:
         if (!recApp.isActive())
            receiveField.setText("Error!");
         else {          
            receiveField.setText("   ");
            ((Receiver)recApp).processInput(sendField.getText());
         }
      }
      else return false;  // event not handled
      return true; // event handled
   }

   // s = number sent by receiver applet
   public void processInput(String s) {
      double y = (Double.valueOf(s)).doubleValue();
      double z = doSomething(y);
      receiveField.setText(String.valueOf(z));
      repaint();
   }

   private double doSomething(double z) { return z + 1; }

}  // Sender

**********************************

// Receiver.java

import java.awt.*;
import java.applet.*;

public class Receiver extends Applet {

   private TextField sendField;    // input field
   private TextField receiveField; // output field

   public void init() {
      setLayout(new FlowLayout());
      sendField = new TextField("SEND", 7);
      add(sendField);
      receiveField = new TextField("RECEIVE", 7);
      add(receiveField);
      // register with MetaContext
      MetaContext.regApplet("receiverapplet", this);
   }

   // s = number sent by sender
   public void processInput(String s) {

      receiveField.setText(s);
      repaint();

      AppletContext context = getAppletContext();
      context.showStatus("***** " + s + " received!");

      // get reference to sender applet
      // Applet senderApp = context.getApplet("senderapplet");
      Applet senderApp = MetaContext.getApplet("senderapplet");

      double x = (Double.valueOf(s)).doubleValue();
      double y = doSomething(x);
      String t = String.valueOf(y);
      sendField.setText(t);
      repaint();

      // send message back to sender applet
      ((Sender)senderApp).processInput(sendField.getText());
     
   }

   private double doSomething(double z) { return z * z; }

}  // Receiver

**********************************

To complete the picture, here are send.html and rec.html:
**********************************

<HTML>
  <TITLE> Sender </TITLE>
  <BODY>

    <P>
        The applet in this frame sends outputs
        to the applet in the other frame.
    </P>

    <APPLET CODE="Sender.class" WIDTH=290 HEIGHT=300 NAME="senderapplet">
       This browser can't run applets.
    </APPLET>

  </BODY>
</HTML>

**********************************

<HTML>
  <TITLE> Receiver </TITLE>
  <BODY>
    <P>
        The applet in this frame receives inputs
        from the applet in the Sender frame.
    </P>


    <APPLET CODE="Receiver.class" WIDTH=290 HEIGHT=300 NAME="receiverapplet">
       This browser can't run applets.
    </APPLET>


  </BODY>
</HTML>

**********************************
 

Written by inquiry.com Staff on 3/21/97.
0
 
JodCommented:
Trouble is, the problem s_venkat_s has is two applets on different web pages so you can't use getappletcontext, but you can still communicate through static variables.
0
 
heyhey_Commented:
> but you can still communicate
> through static variables.

you can use static varables if you applets are loaded from the same classloader (usually you have one classloader per codebase)

otherwise you can comminicate through server app - or if you can sign your applets you can use some Socket based communication.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 10
  • 9
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now