Java Button Applet

The GUI components can be placed in a frame or an applet (as both are containers). We have seen many programs with frame and now let us write an applet with GUI, say button. While developing applet GUI, the class should extend Applet instead of Frame. The constructor is replaced with init() method.

In the following example, when the button "Click And Count" is clicked, a counter is maintained and the counter is displayed as a label.

Program on Java Button Applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonApplet extends Applet implements ActionListener
  Button btn;
  Label lab;
  int counter;                                          // by default assigned with 0
  public void init()
    btn = new Button("Click And Count");
    lab = new Label("You click, I count");

    add(btn);   add (lab);
   public void actionPerformed(ActionEvent e)
     lab.setText("Your click count: " + counter++);

File Name: BA.html


Java Button Applet

Figure: Applet run in a browser

Java Button Applet

Figure: Applet run in appletviewer

A button, btn, with "Click And Count" is created and added to the applet. At the same time, a label lab is also created and added and this label is used to display the number of clicks. Both are added in FlowLayout, the default layout manager of Applet. setText() is a method of Label class which changes the text of the label.

Detailed discussion on event handling steps is given in "Java AWT Button – Learning GUI – 8 Steps".

Note: The applet window closing does not require extra coding. The window closes by default.

2 thoughts on “Java Button Applet”

Leave a Comment

Your email address will not be published.