Standard event handling: – We can add new button with the text “Click Me!” to an applet as well as adding an action listener that will be notify when the button clicks. To add an action listener to the button, we use button’s addActionListener method, passing it to an object that implements the method of the ActionListener interface. This object can be an object of the applets main class or another class. We can construct text field with a button using java applet in the following format –

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Applet2 extends Applet implements ActionListener
{
                TextField text1;Button button1;
                public void init()
                {
                                text1=new TextField(20);
                                add(text1);
                                button1=new Button("Click Here!");
                                add(button1);
                                button1.addActionListener(this);
                }
                public void actionPerformed(ActionEvent event)
                {
                                String msg=new String("Hello from Java!");
                                if(event.getSource()==button1)
                                {
                                                text1.setText(msg);
                                }
                }
}

 

<HTML>
                <APPLET
                                CODE=Applet2.class
                                WIDTH=200
                                HEIGHT=150>
                </APPLET>
</HTML>

Applet Button.PNG

Advertisements