开发者

Communication between Applets

Please check these code samples:

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

public class pp extends Applet implements ActionListener
{
    TextField t;
    Button    b;

    public void init()     
    {
        setLayout(new FlowLayout());
        t= new TextField(10 );
        b = new Button("Send");
        b.addActionListener(this);
        add(t);
        add(b);
    }

    public void actionPerformed(ActionEvent e) 
    {
        String str=t.getText();
        dc a2 =(dc)getAppletContext().getApplet("a2");
           if ( a2 != null ) 
               {
                  a2.append(str);
               }
           else 
           {
              System.out.println("Applet not found?");
           }
     }
}

and the 2nd applet code:

import java.applet.*;
import java.awt.*;
开发者_JAVA技巧import java.awt.event.*;
/*<Applet code="dc" height=400 width=400></Applet>*/
public class dc extends Applet
{
    TextArea t;

    public void init()
    {
        setLayout(new FlowLayout());
        t=new TextArea(5,40);
        add(t);
    }

    public void append(String msg)
    {
        t.setText(msg);
    }
}

and here is the HTML code:

<HTML><HEAD></HEAD><BODY>
<APPLET CODE="pp.class"   
    HEIGHT=200 WIDTH=150>
</APPLET>
<APPLET CODE="dc.class"  
    HEIGHT=200 WIDTH=400>
</APPLET>
</BODY></HEAD>

Don't know why it doesn't work. This program is writeen for communication between the two applets in the same page. Can anyone tell me what is wrong here?


See Inter applet communication

This looks very similar to what you are doing.


First applet:

import java.awt.*;
import java.applet.*;
public class ONE extends Applet
{
    TextArea ta;
    public void init()
    {
        ta=new TextArea(" ");
        add(ta);
    }
    public void putText(String s)
    {
        ta.appendText(s+"\n");
    }
}

Second applet:

import java.io.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;


public class TWO extends Applet implements ActionListener
{
    TextField tf;
    Applet r;
    Button b;
    public void init()
    {
        tf=new TextField(20);
        add(tf);
        b=new Button("SUMBIT");
        add(b);
        b.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e)
    {   r=null;
        r= getAppletContext().getApplet("ONE");
        if (r!=null)
        {
            if(e.getSource()==b)
            {
                ONE ma= (ONE) r;
                ma.putText(tf.getText());
                tf.setText("");
            }
        }       
    }
}

Use the above code in action performed.

HTML:

<html>
<body>
<applet code="TWO" width = 150 height=150 name=TWO>
</applet>
<br></br>
<br></br>
<br></br>
<applet code="ONE" width = 200 height=200 name=ONE>
</applet>
</body>
</html>

Run it using appletviewer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜