Java Applet program to display the Button

In this tutorial we shall learn about buttons in applet and handling those buttons.As a simple task we shall make a program “which show the users the button which he has clicked”.For this we need button in applet.The declaration of button in applet is as follows:

Button click = new Button("Click me");

Each button has it’s role,so we need to define the role played by the button.Here we have given the button the label “click me”.Therefore a button appears with “click me” text inside it.After declaration of the button we need to add the button to the applet window.For this we use the function add() which is invoked by the object of the element.Here the element is button and the object declared is click.Hence to add the element we use “click.add(this);”.

Every action performed in the applet is heard by the actionListener method.So to listen the action performed by the button we need to add the actionListener using addActionListener(),this is invoked by the object of the respective element.

After clicking the button the control is passed to the actionPerformed() method which takes object of the ActionEvent class as a parameter.There we use the method getActionCommand() to get the text which is assigned to that button during declaration and stores it in a global string. TO display the button which is clicked we are going to use the textfield in applet and we shall set the text of the TextField to the global string.Declaration of TextField and Label is as follows

Label lb = new Label("Selected Button is");
TextField tf = new TextField(20); // size of the textfield

The program is:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
<applet code = "Button_selected_displayed.class" width = 500 height = 500>
public class Button_selected_displayed extends Applet implements ActionListener
   String str="";
   Button b1,b2,b3;
   Label lb;
   TextField tf;
   public void init()
	b1 = new Button("Hello world");
	b2 = new Button("Hello java");
	b3 = new Button("Exit this world");
                  lb = new Label("Selected Button  is:");
                  tf = new TextField(25);
public void actionPerformed(ActionEvent ob)
   str = ob.getActionCommand();
public void paint(Graphics g)




Download the source code


About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s