Preparing to Launch Our Java Applet And Handle Events - Java
With the skills that you have developed so far from Part I of the tutorial, you can design a graphical user interface with beauty and easy. Let us refresh ourselves before we proceed, Events are method calls that Javas windowing system performs whenever any element of a user interface is manipulated.
Example 6: Save As RadioTest.java, Compile And View Using Appletviewer
In this Applet example we examine MouseAdapters, and its methods like mouseClicked(). Plus ItemListener interface implementation and itemStateChanged() method and use getItem() method to display the item the user as selected in the Applet’s status bar using the showStatus()method. We will use interface components like checkbox, which are of two types-exclusive checkboxes (which means only one among the group can be selected) also called Radio Buttons. We also use non-inclusive checkboxes, which can be selected independently. The Choice class implements the pop-up menu that allows users to select items from a menu. This UI component dispalys the currently selected item with a arrow to its right.
/*
<applet code = "RadioTest.class" height = 300 width = 300 >
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RadioTest extends Applet
{
public void init()
{
CheckboxGroup cbg = new CheckboxGroup();
// Checkbox(label, specific checkgroup, checked:boolean)
Checkbox c1 = new Checkbox("Black and White",cbg,false);
Checkbox c2 = new Checkbox("Color",cbg,false);
//adding mouselistener to the corresponding
// component to trap the event
c1.addMouseListener(new check1());
c2.addMouseListener(new check2());
//adding components to the container
add(c1);
add(c2);
//To create a Choice Menu(say to list the various choices)
// a Choice Object is instantiated.
// In short-Choice() constructor creates a new choice menu
//& you add items using addITem()
Choice c = new Choice();
c.add("LG");
c.add("Onida");
c.add("BPL");
c.add("Samsung");
c.add("Philips");
c.add("Sony");
// adding ItemListener to choice then adding it to the container
c.addItemListener(new Ch());
add(c);
}
Class check1 extends MouseAdapter
{
Public void mouseClicked(MouseEvent e)
{
showStatus("You have selected Black & White TV option");
}
}
Class check2 extends MouseAdapter
{
Public void mouseClicked(MouseEvent e)
{
showStatus("You have selected Color TV option");
}
}
Class Ch implements ItemListener
{
Public void itemStateChanged(ItemEvent e)
{
String s =(String)e.getItem();
showStatus("You have selected" + s + " brand for your TV");
}
}
}
Hope you got a fair idea of what Event-Handling is all about. In addition,
We have also dealt elaborately with Adapter classes and inner classes to help you write simplified codes on Java’s Event-Handling. If you still feel you haven’t got the groove of it, don’t worry read the article again and experiment with some codes on your own. For experience is the best teacher.