Send a Message to Another Applet
will see that we can send messages between applets that are loaded on the same page, so we can separate various functions in different Applets and to send information, objects and even components Applet to another.
In this case the first applet invokes a method on the second applet by passing as parameter a String, this String is added to the JComboBox the second applet. Images
In this case the first applet invokes a method on the second applet by passing as parameter a String, this String is added to the JComboBox the second applet. Images
Code
Applet 1
Master Class
Classes package;
java.awt.FlowLayout import, import
java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing .*;
public class Main extends JApplet {
JTextField txt;
JButton b;
public void init () {
setLayout (new FlowLayout ());
txt = new JTextField ("", 15);
b = new JButton ("Send Message");
b.addActionListener (new ActionListener () {
@ Override
public void actionPerformed (ActionEvent e) {
Principal2 applet2 =(Principal2)getAppletContext().getApplet("applet2");
if ( applet2 != null ) {
applet2.AgregarDato( txt.getText() );
}
}
});
add(txt);
add (b);}
}
Class Principal2
Applet2
package classes;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class Principal2 extends java.applet.Applet {
JComboBox combo;
public void init() {
setLayout(new FlowLayout());
combo=new JComboBox();
add(new JLabel("Datos: "));
add(combo);
}
public void AgregarDato( String m ) {
combo.addItem (m);
combo.updateUI ();
repaint ();
}}
The first applet which does is create a text field, where typing the message and a button which when clicked will send the typed message. Gets the instance of the applet called applet2, this name is specified to be posted on the page in the html tag. It then calls the method of the Applet AgregarDato 2 to add a fact to JComboBox.
The second applet, the only thing it does is create a JComboBox which show the data sent by the first applet.
Applet 1
Applet 2
0 comments:
Post a Comment