You are on page 1of 50

Basic Programming using Java

Event Handling in AWT

Event Handling in AWT


At the end of this chapter you will be able to understand various types of events associated with AWT components and how to handle them.

SCOPE
8.1 Event Handling in Java 8.2 Handling Mouse Clicks 8.3 Handling Mouse Movements 8.4 Handling Keyboard Events 8.5 Handling Component Events 8.5.1 Handling Buttons 8.5.2 Handling Checkboxes and Radio buttons 8.5.3 Handling Choices and Lists 8.5.4 Handling Scrollbars 8.5.5 Handling Windows, Frames and Dialog boxes 8.5.5.1 Frame 8.5.5.2 Dialog 8.5.6 Case Study College Student Enrolment System (Contd.) 8.5.7 Handling Menus

Basic Programming using Java

Event Handling in AWT

8.1 Event Handling in Java


In Chapter 7, an introduction to creating AWT components was given. With the help of AWT you can create components like Buttons, Labels, Checkboxes, Radio buttons, etc. But it is equally important to handle the user response to these components. For example, if a checkbox has been checked, the program should be able to record this information. In this case clicking of the checkbox is an event. An event is generated in response to anything that a user does, when a program is running. For example, the movement of mouse, button click, a key press - all of these activities generate different types of events. Events can be broadly categorized into four categories: Mouse Click Event mouse is pressed down or released or is clicked (pressed and released both at the same location) Mouse Movements mouse is moved or dragged (pressed down and moved) Keypresses a key is pressed, released, or typed (pressed and released both) User-interface events a button is clicked, checkbox is checked, scroll bar is moved up and down Each type of event is handled differently by Java 1.1 and Java 1.2 Event model. Java 1.1 and 1.2 event model is very different from Java 1.0 event model. In Java 1.0 Event model, an object that needs to handle events has to be a sub-class of Component class. This restriction is not there in Java 1.1 and 1.2 Event model. Here any class can receive and manage events even if it is not a sub-class of Component class. This is done because many times an event is handled by some other object. For example a button click might trigger an action in an object other than the button. For this purpose Java 1.1 and 1.2 Event model support the Event Listeners. This event model is also called as Delegation Event Model as it allows you to designate any object to be an event listener. You can completely control how events are transmitted from the event sources (such as buttons, lists) to event listeners. An Event Listener is any object that implements one or more listener interfaces. There are different listeners for each category of AWT components. For example, MouseListener will be able to receive mouse clicks and MouseMotionListener will be able to receive mouse movements. Similarly there are other listeners for many other AWT components. Event sources have methods that allow you to register event listeners with them. When an event happens to the source, the source sends the notification of that event to all the listener objects that are registered for that event. The information about the event is encapsulated in the event object (all event objects ultimately derive from the class java.util.EventObject). Basic steps for event handling in Java 1.2 model can be given as: Listener object is an instance of a class that implements a listener interface, which includes methods to be called when an event is triggered. The eleven listener interfaces are: ActionListener KeyListener MouseListener AdjustmentListener ComponentListener MouseMotionListener ContainerListener TextListener

Basic Programming using Java

Event Handling in AWT

For example,
Class UPanel extends Panel implements ActionListener{ public void actionPerformed(ActionEvent e){ } }

An event source is an object that can register listener objects and send them event objects. To register event listener object with event source the following syntax is used
eventSourceObj.addEventListener(eventListenerObj); For example, UPanel panel1 = new UPanel(); Button button1 = new Button(Ok); button1.addActionListener(panel1);

Statement button1.addActionListener(panel1), registers the event actionlistener object panel1, with event source button1. When the event occurs event source sends out event objects to all registered listeners. For example, When the user presses Ok button an ActionEvent object is created and panel1.actionPerformed is called with ActionEvent object as a parameter. The listener objects then use the information in the event object to respond to the event.
UPanel ActionListener Interface actionPerformed() 1 UPanel object is passed to Ok buttons addActionListener () method

2 Button press causes actionPerformed() of listeners to be called

addActionListener () Fig 8.1 Steps in Java 1.2 Event Model

Let us now see how each of these types of events are handled by Java 1.1(and 1.2) Event model.

8.2 Handling Mouse Clicks

Basic Programming using Java

Event Handling in AWT

Mouse click is one of the most common events since most of the environments today are GUI environments. One can use mouse clicks to do a variety of things like clearing the screen, displaying a shortcut menu or help, turning sound on or off, etc. The MouseListener interface can be used to handle mouse clicks. In case an applet wants to tap mouse click events, it must implement MouseListener interface. This interface has five methods, all of which must be overridden by the applet. These methods are:
public abstract invoked when public abstract invoked when public abstract invoked when public abstract invoked when public abstract invoked when void mouseClicked(MouseEvent e) the mouse is clicked on a component void mousePressed(MouseEvent e) the mouse button is pressed on a component void mouseReleased(MouseEvent e) the mouse button is released on a component void mouseEntered(MouseEvent e) the mouse enters a component void mouseExited(MouseEvent e) the mouse exits a component

All of these methods take as an argument an object of class MouseEvent. From this object one can get the x and y coordinates of the position where the mouse click event happened. The MouseEvent class has certain methods which are given below, to find out the x and y coordinates of the position, how many number of times the mouse was clicked, etc.
public int getX() returns the x position of the event relative to source component public int getY() returns the y position of the event relative to source component public Point getPoint() returns the x,y position of the event relative to source component public synchronized void translatePoint(int x, int y) adds the x value to current x position and y value to current y position public int getClickCount() returns the number of times the mouse was clicked public boolean isPopupTrigger() returns whether this mouse event is the popup-menu trigger event

To understand how a mouse click event is trapped, let us write a program (refer to program listing 8.1) that prints Clicked 1 when a mouse is clicked once, Clicked 2 when it is clicked twice and so on.
import java.awt.*; import java.awt.event.*;

Basic Programming using Java

Event Handling in AWT

public class Mouseclick MouseListener{ Point p=null; int numOfClicks=0;

extends

java.applet.Applet

implements

public void init(){ setBackground(Color.white); addMouseListener(this); } public void mousePressed(MouseEvent me){ public void mouseReleased(MouseEvent me){ public void mouseEntered(MouseEvent e) { public void mouseExited(MouseEvent e) { public void mouseClicked(MouseEvent e) { p=new Point(e.getPoint()); numOfClicks=e.getClickCount(); repaint(); } } } } }

public void paint(Graphics g){ g.setColor(Color.red); if (p != null) g.drawString("Clicked "+numOfClicks, p.x, p.y); public void destroy(){ removeMouseListener(this); }
Listing 8.1 Handling mouse clicks

Since the applet has to receive mouse click events, MouseListener interface has been implemented. The init() method of the applet uses addMouseListener() method to add mouse listener to the component. Similarly removeMouseListener() methods remove that mouse listener from the component. The paint() method of the applet simply prints how many number of times the mouse was clicked. This information is supplied by the mouseClicked() method of MouseListener interface. Since all the methods of MouseListener interface must be overridden, all the other methods are left blank. Since the mouse click event can be tapped in a component other than Applet, the part of the program that handles the mouse click can be made a separate class. Then an object of that class can be used in the applet to print the string. Program listing 8.2 and 8.3 given below shows this way of writing the mouse click program (refer to listing 8.1).
import java.awt.*; import java.awt.event.*; public class ClickSetter1 implements MouseListener{ Component c; Point p; int n; ClickSetter1(Component c){ this.c=c;

Basic Programming using Java

Event Handling in AWT

} public void mouseClicked(MouseEvent e){ p=new Point(e.getPoint()); n=e.getClickCount(); c.repaint(); } public void mousePressed(MouseEvent me){ public void mouseReleased(MouseEvent me){ public void mouseEntered(MouseEvent e) { public void mouseExited(MouseEvent e) { }
Listing 8.2 Defining class that will handle the mouse click event

} } } }

import java.awt.*; public class Try1 extends java.applet.Applet{ ClickSetter1 b=new ClickSetter1(this); public void init(){ addMouseListener(b); } public void paint(Graphics g){ if (b.p !=null) g.drawString("Clicked "+b.n,b.p.x,b.p.y); public void destroy(){ removeMouseListener(b); } }

Listing 8.3 Defining classes that will use the object that handles the mouse clicks

This way an object of class ClickSetter1 can be used in any class, which makes the method of handling mouse clicks reusable. The try1.java program creates an object of class ClickSetter1 and passes the reference of the current applet as an argument to it. As a result the variable c of ClickSetter1 class gets the reference of current applet. Then try1.java program adds the mouse listener during the initialisation process and removes it during the destruction process of the applet. The paint() method of the applet checks if the point at which the string has to be printed is null or not. Since the point is stored in ClickSetter1 object b, b.p can be used to get the value of the Point object. Similarly to get the x and y coordinates of the point where the mouse was clicked, one can use b.p.x and b.p.y and use it in drawString() method. But note that in ClickSetter1 class even when the methods, apart from mouseClicked() method, are not used, they have to be overridden. Java also provides Adapters apart from Listeners. Adapters are another way of implementing Listeners. The only difference between the two is that in Adapters you dont have to override all the methods. You can override just those methods that you need in your program. Program listing 8.4 and 8.5 shows how MouseAdapter can be used in place of MouseListener in the mouse click program. In the listing 8.4 since the class ClickSetter2 extends from MouseAdapter class, only the methods of interest can be overridden.

Basic Programming using Java

Event Handling in AWT

import java.awt.*; import java.awt.event.*; public class ClickSetter2 extends MouseAdapter{ Component c; Point p; int n; ClickSetter2(Component c){ this.c=c; } public void mouseClicked(MouseEvent e){ p=new Point(e.getPoint()); n=e.getClickCount(); c.repaint(); } }
Listing 8.4 Creating subclass of MouseAdapter class that will handle mouse clicks

import java.awt.*; public class Try2 extends java.applet.Applet{ ClickSetter2 b=new ClickSetter2(this); public void init(){ addMouseListener(b);

public void paint(Graphics g){ if (b.p !=null) g.drawString("Clicked "+b.n,b.p.x,b.p.y); public void destroy(){ removeMouseListener(b); }
Listing 8.5 Program that will use an object of class clickSetter2

Basic Programming using Java

Event Handling in AWT

8.3 Handling Mouse Movements


There are basically two mouse movements dragging a mouse and simply moving mouse over the surface. Both of these mouse movements can be trapped by either implementing MouseMotionListener interface or by extending MouseMotionAdapter class. The MouseMotionListener interface has the following two methods:
public abstract void mouseDragged(MouseEvent e) called when the mouse button is pressed on a component and then dragged public abstract void mouseMoved(MouseEvent e) called when the mouse is moved over a component

The program listing (listing 8.6) given below shows an applet on which lines can be drawn. The applet will draw a maximum of 20 lines and the current line will be drawn in red colour whereas the rest of the lines will be in black colour.
import java.awt.*; import java.awt.event.*; public class MouseEvent2 extends java.applet.Applet{ int MAXLINES = 20; Point start[]=new Point[MAXLINES]; Point end[]=new Point[MAXLINES]; Point currstart, currend; int currline=0; HandleMouseEvent h=new HandleMouseEvent(); public void init(){ setBackground(Color.white); addMouseListener(h); addMouseMotionListener(h); } public void paint(Graphics g){ for (int i=0;i<currline;i++) g.drawLine(start[i].x, start[i].y, end[i].x, end[i].y); g.setColor(Color.red); if (currend != null) g.drawLine(currstart.x, currstart.y, currend.x, currend.y); } public void destroy(){ removeMouseListener(h); removeMouseMotionListener(h); } public class HandleMouseEvent extends MouseAdapter implements MouseMotionListener{ public void mousePressed(MouseEvent me){ if (currline<MAXLINES) currstart=new Point(me.getPoint());

Basic Programming using Java

Event Handling in AWT

} public void mouseReleased(MouseEvent me){ if (currline<MAXLINES){ start[currline]=currstart; end[currline]=currend; currline++; currstart=currend=null; repaint(); } } public void mouseDragged(MouseEvent me){ if (currline<MAXLINES){ currend=new Point(me.getPoint()); repaint(); } } public void mouseMoved(MouseEvent e){} } }
Listing 8.6 Program that will draw line from the point where the mouse button was pressed till where it was dragged

In the program listing 8.6, currstart and currend store the starting and end position of the current line. The variable currstart is assigned a value when the mouse button is pressed and currend is assigned a value when the mouse button is dragged so that the current line can be drawn. These start and end points are then added to the start[] and end[] array once the mouse has been released. These lines and the current line is the drawn in the paint() method.

8.4 Handling Keyboard events


To handle keyboard events in Java 1.1 and 1.2 Event model, you need to implement KeyListener interface or by extending KeyAdapter class. The KeyListener interface has the following methods to receive keyboard events:
public abstract invoked when public abstract invoked when public abstract invoked when and released void keyPressed (KeyEvent e) a key is pressed from the keyboard void keyReleased (KeyEvent e) a key is released after it has been pressed void keyTyped (KeyEvent e) the key is typed from the keyboard (pressed both)

The KeyEvent class has the following methods:


public int getKeyCode() returns the integer key code associated with the key public void setKeyCode(int keyCode) sets the integer key code public void setKeyChar(char keyChar) sets the character key code

Basic Programming using Java

Event Handling in AWT

public char getKeyChar() returns the character representation of the key, returns CHAR_UNDEFINED if no valid unicode character exist for this key event public static String getKeyText(int keyCode) returns a String describing the key code, e.g., HOME, END, F5, A, etc. public static String getKeyModifiersText(int modifiers) returns the String describing the modifier ker, like Shift, Ctrl or Shift+Ctrl public boolean isActionKey() returns whether or not the key in the event is an action key. Action keys are cursor movements keys like Uparrow, Downarrow, Home, etc., function keys (F1-F12), PrintScreen key, and the lock keys (Caps, Num, Scroll)

Since keycodes vary from system to system, Java defines its own codes for common keys. Refer to Java API to get the keycodes for keys on the keyboard. Program given below (listing 8.7) traps the key that is entered when the applet runs and prints it on the applet screen.
import java.awt.*; import java.awt.event.*; public class TryKey extends java.applet.Applet{ String key; Font f; public void init(){ f=new Font("TimesRoman",Font.BOLD,28); setBackground(Color.white); setForeground(Color.blue); setFont(f); TryKey.this.addKeyListener(new KeyListener(){ public void keyTyped(KeyEvent e){ int ch=e.getKeyChar(); if ((ch>='A' && ch<='Z') || (ch>='a' && ch<='z') || (ch>='0' && ch<='9')) key=(char)ch+" "; else key=e.getKeyText(ch); repaint(); } public void keyPressed(KeyEvent e){} public void keyReleased(KeyEvent e){} }); } public void paint(Graphics g){ g.drawString("Key is "+key,10,40); }

Basic Programming using Java

Event Handling in AWT

}
Listing 8.7 Trapping keys from keyboard

The applets init() method sets the background colour, foreground colours and the font. The applet has a String variable key, which will hold the key, pressed and the paint() method prints that value on the screen. A KeyListener has been added to the applet by using addKeyListener() method in the same way as MouseListener was added (refer to listing 8.2 and 8.3). However, in program listing 8.2, we created a class that implemented MouseListener interface in which we defined the methods to handle mouse events. But in this program instead of creating a separate class, the code that has to be written in that class is written inside the addKeyListener() method only. We can write the above code (listing 8.7) in a different way also. Before init() method one can say:
KeyListener k=new KeyListener(){ public void keyTyped(KeyEvent e){ int ch=e.getKeyChar(); if ((ch>='A' && ch<='Z') || (ch>='a' && ch<='z') || (ch>='0' && ch<='9')) key=(char)ch+" "; else key=e.getKeyText(ch); repaint(); } public void keyPressed(KeyEvent e){} public void keyReleased(KeyEvent e){} });

and then KeyListener can be added in init() method as follows:


trykey.this.addKeyListener(k);

As a result of this program, keys A-Z, 0-9, a-z, and the keys that have equivalent text like Tab, Enter, etc. would be printed .

8.5 Handling Component Events


We already know what components are and how can they be used to create user-friendly applications and applets. However, so far we have dealt only with the creation of these components in chapter 7, let us now see how functionality can be added to these components. Figure given below (refer to fig. 8.2) shows the hierarchy of the Component class and its subclasses.

Basic Programming using Java

Event Handling in AWT

Component

Canvas Button

Choice Checkbox

Container Label

List Scrollbar

TextComponent

Panel

ScrollPane

Window

TextArea

TextField

Applet

Frame

Dialog

FileDialog
Fig. 8.2 Hierarchy of Components class

The handling of most of these components is almost alike, therefore, we will be discussing about some of the most frequently used components.

Basic Programming using Java

Event Handling in AWT

8.5.1

Handling Buttons

Buttons are fundamental GUI components. No application is complete without them. They are needed to get user response about something, whether it is asking the user to confirm delete operation or confirm saving of a file or any other thing. That is why it becomes necessary to handle the event that is caused by button click. The Button class of java.awt package provides the users with the facility of creating labelled buttons. To be able to trap button click event, an ActionListener must be associated with the button. This ActionListener can be added to the button with the help of addActionListener() method of Button class. Similarly removeActionListener() method can be used to remove the Action Listener from the Button object. We have already seen how animation is created with the help of threads. We will now write a Java applet that has three buttons Play, Loop and Stop. On clicking Play button, the animation starts and on clicking Loop button, the animation starts running in a loop till the Stop button is clicked or the applet is exited or stopped. The animation consists of displaying 10 images and playing a sound in the background. Program listing 8.8 does such a thing.
import java.awt.*; import java.awt.event.*; import java.applet.AudioClip; public class Anim extends java.applet.Applet implements Runnable{ Thread t; Image img[]=new Image[10]; Image currimage; AudioClip c; char ch; Button playButton=new Button("Play"); Button stopButton=new Button("Stop"); Button loopButton=new Button("Loop"); public void init(){ String imgsrc[]={"T1.GIF","T2.GIF","T3.GIF", "T4.GIF","T5.GIF","T6.GIF","T7.GIF", "T8.GIF","T9.GIF","T10.GIF"}; for (int i=0;i<10;i++) img[i]=getImage(getCodeBase(),"image/"+imgsrc[i]); c=getAudioClip(getCodeBase(),"image/spacemusic.au"); playButton.addActionListener(new ButtonHandler()); stopButton.addActionListener(new ButtonHandler()); loopButton.addActionListener(new ButtonHandler()); add(playButton); add(stopButton); add(loopButton); } public void dostart(){

Basic Programming using Java

Event Handling in AWT

t=new Thread(this); t.start(); } public void stop(){ t=null; c.stop(); } public void run(){ int i=0; Thread currThread=Thread.currentThread(); c.loop(); while (t==currThread){ currimage=img[i]; repaint(); try{ Thread.sleep(1000); } catch(InterruptedException e) {} i++; if (ch=='P') if (i==10) stop(); if (ch=='L') if (i==10) i=0; } } public void paint(Graphics g){ if (currimage !=null) g.drawImage(currimage,10,60,this); } class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if ("Play".equals(s)) { ch='P'; dostart(); } else if ("Stop".equals(s)) stop(); else if ("Loop".equals(s)) { ch='L'; dostart(); }; } } }
Listing 8.8 Running and stopping animation with the help of buttons

Basic Programming using Java

Event Handling in AWT

This program is very much the same as any animation program created in chapter 6. The difference is that three buttons have been added in the beginning and an object of ButtonHandler class has been added as the ActionListener to each of these buttons. The ActionListener interface has only one method. The prototype of this method is given below:
public void abstract actionPerformed(ActionEvent e)

The ActionEvent class has a method called getActionCommand() that returns the command name associated with this event. The method actionPerformed() is overridden in listing 8.8 to get the action command associated with the event. If this action command is Play dostart() method is called and variable ch is initialised with a value P. If it is Loop, the variable ch gets a value L and dostart() method is again called. Lastly if the action command is Stop, the stop() method of the applet is called that stops the thread that is creating the animation and stops the playing of the music too. The dostart() method in turn creates a new thread and starts running it. The thread shows the images stored in files T1.GIF to T10.GIF in a loop if the variable ch has a value L or simply till T10.GIF if the variable ch has a value P. The thread also plays the sound in a

loop. Fig. 8.3 given below shows this applet running in a browser.
Fig. 8.3 Applet displaying buttons

8.5.2

Handling Checkboxes and Radio Buttons

A Checkbox item is displayed as a square brackets with a label. This square bracket has a tick against it if the checkbox item is selected. Checkbox items are suitable when you want to ask a question from the user that has only two answers true or false, on or off, yes or no. For example, one can have the item Shipped the goods as a Checkbox item since either the goods have been shipped or they have not been. There can be no third value for this item. A radio button is an item that can have one and only one answer from a given set of choices. For example, in a payment application, the mode of payment can either be Cash

Basic Programming using Java

Event Handling in AWT

or Cheque or Demand Draft. One cannot pay by all three means. Ideally a radio button. Can be used in this situation. When many Checkbox items are associated with a CheckboxGroup, it becomes a radio button. Then only one of those items can be selected by the user at runtime. A CheckboxGroup or a radio button is displayed as a set of items with a bullet in front of them. At one point of time only one of these items can be bulleted. Let us first take an example where we will be using Checkboxes and we will use a TextArea object to hold the result. For this purpose we will create a class called CheckboxPanel, which extends from Panel class. As all of us know a Panel is a container that can hold one or more components. The program listing 8.9 creates class CheckboxPanel.
import java.awt.*; import java.awt.event.*; public class CheckboxPanel extends Panel{ public CheckboxPanel(String title, String names[], orientation, ItemListener il){ super(); int l=names.length; if (orientation==0) //horizontal setLayout(new GridLayout(1,l+1)); else setLayout(new GridLayout(l+1,1)); add( new Label(title)); for (int i=0; i<l;i++){ Checkbox c=new Checkbox(names[i]); c.addItemListener(il); add(c); } } public CheckboxPanel(String title, String names[], orientation, ItemListener il, boolean state[]){ super(); int l=names.length; if (orientation==0) //horizontal setLayout(new GridLayout(1,l+1)); else setLayout(new GridLayout(l+1,1)); add( new Label(title)); for (int i=0; i<l;i++){ Checkbox c=new Checkbox(names[i],state[i]); c.addItemListener(il); add(c); } } public boolean getState(String label){ Checkbox items[]=(Checkbox[])getComponents(); for (int i=0;i<items.length;i++) if (label.equals(items[i].getLabel())) return items[i].getState(); int

int

Basic Programming using Java

Event Handling in AWT

return false; } public void setState(String label,boolean val){ Checkbox items[]=(Checkbox[])getComponents(); for (int i=0;i<items.length;i++) if (label.equals(items[i].getLabel())) items[i].setState(val); } }
Listing 8.9 CheckboxPanel class that creates checkboxes

In program listing 8.9, two constructor methods have been used, The first constructor method accepts a String which will serve as the title or heading for the Checkbox items, an array of Strings that will serve as the label for the Checkbox items, the orientation of the items (horizontal or vertical), and an ItemListener object reference that will trap the Checkbox related events. This constructor creates the layout for the panel depending on the orientation. If the orientation is horizontal, a GridLayout is created having as many number of columns as the Checkbox items. If the orientation is vertical, a GridLayout is created having as many number of rows as the Checkbox items. Then a label is added to the panel that will have the text, as that passed in the String object. Next, Checkbox items are created and ItemListener is added to each item. The second constructor takes one more argument than the first constructor a boolean array containing the states of each Checkbox item. The working of this constructor is same as the first one except that each Checkbox either checked or unchecked depending on the state of that item. This class has two methods getState() and setState(). The getState() method accepts a String and returns the state of Checkbox item represented by that String. The setState() method accepts a String and a Boolean value and sets the state of the Checkbox item represented by that String with that Boolean value. Now we need to create an applet that will use this class to create Checkboxes. Listing 8.10 shows an applet program that uses this class to create Checkboxes and displays the choice of the user in a TextArea item.
import java.awt.*; import java.awt.event.*; import java.applet.*; public class CheckBox1 extends java.applet.Applet{ CheckboxPanel cpanel; TextArea ta=new TextArea(5,20); public void init(){ setLayout(new BorderLayout()); CheckboxHandler ch=new CheckboxHandler(); String hobbies[]={"Sports","Reading","Traveling","Painting", "Dancing"}; cpanel=new CheckboxPanel("Your hobbies?",hobbies,1,ch); add(cpanel,"West");

Basic Programming using Java

Event Handling in AWT

add(ta,"South"); } class CheckboxHandler implements ItemListener{ public void itemStateChanged(ItemEvent e){ String currstatus; Checkbox c=(Checkbox) e.getItemSelectable(); if (c.getState()) currstatus="You checked : "; else currstatus="You unchecked : "; currstatus=currstatus+c.getLabel(); ta.setText(currstatus); } } }
Listing 8.10 Using CheckboxPanel to create checkboxes

Fig. 8.4 Applet displaying Checkboxes

This class shows a CheckboxPanel object being created with arguments, title as Your hobbies?, an array called hobbies, vertical orientation (denoted by number 1) and an object of a class that implements ItemListener. It also adds a TextArea object to the applet. The class that implements ItemListener interface overrides the itemStateChanged() method. This method traps the event in an object of ItemEvent class. ItemEvent class has a method called getItemSelectable() that returns the item on which the event was called. The itemStateChanged() method finds the Checkbox item on which the event was called and checks the state of that item. If it was checked, getState() method returns a value true and currstatus String gets a value You checked: otherwise it gets a value You unchecked:. Then the label of the Checkbox item is also added to the currstatus String to get the item on which the event was clicked. This is done by using getLabel() method of Checkbox class.

Basic Programming using Java

Event Handling in AWT

The TextArea object is then set with the value in currstatus String. Fig. 8.4 shows the output of this program in the browser. Since the class CheckBoxPanel is in the same directory, there is no need to import it in this program. We will now write another class called CheckboxGroupPanel that will create radio buttons. Listing 8.11 shows the code for this class. The working of this class is similar to that of CheckboxPanel class. The only difference is that all of the Checkbox items are added to a CheckboxGroup to create a radio button.
import java.awt.*; import java.awt.event.*; public class CheckboxGroupPanel extends Panel{ public CheckboxGroupPanel(String title, String names[], int orientation, ItemListener il){ super(); int l=names.length; if (orientation==0) //horizontal setLayout(new GridLayout(1,l+1)); else setLayout(new GridLayout(l+1,1)); add( new Label(title)); CheckboxGroup cg=new CheckboxGroup(); for (int i=0; i<l;i++){ Checkbox c=new Checkbox(names[i],false,cg); c.addItemListener(il); add(c); } } public CheckboxGroupPanel(String title, String names[], int orientation, ItemListener il, boolean state[]){ super(); int l=names.length; if (orientation==0) //horizontal setLayout(new GridLayout(1,l+1)); else setLayout(new GridLayout(l+1,1)); add( new Label(title)); CheckboxGroup cg=new CheckboxGroup(); for (int i=0; i<l;i++){ Checkbox c=new Checkbox(names[i],state[i],cg); c.addItemListener(il); add(c); } } public boolean getState(String label){ Checkbox items[]=(Checkbox[])getComponents(); for (int i=0;i<items.length;i++) if (label.equals(items[i].getLabel())) return items[i].getState(); return false;

Basic Programming using Java

Event Handling in AWT

} public void setState(String label,boolean val){ Checkbox items[]=(Checkbox[])getComponents(); for (int i=0;i<items.length;i++) if (label.equals(items[i].getLabel())) items[i].setState(val); }

}
Listing 8.11 Creating CheckBoxGroupPanel class

To use this class for creating radio buttons, the following program listing (listing 8.12) can be used. It creates a CheckboxGroup and a TextArea item, which shows the choice entered by the user at runtime.
import java.awt.*; import java.awt.event.*; import java.applet.*; public class CheckBox2 extends java.applet.Applet{ CheckboxGroupPanel cgpanel; TextArea ta=new TextArea(5,20); public void init(){ setLayout(new BorderLayout()); CheckboxHandler ch=new CheckboxHandler(); String ages[]={"less than 20","20-29","30-39","40-49","50 or above"}; cgpanel=new CheckboxGroupPanel("Your age?",ages,0,ch); add(cgpanel,"East"); add(ta,"South"); } class CheckboxHandler implements ItemListener{ public void itemStateChanged(ItemEvent e){ String currstatus; Checkbox c=(Checkbox) e.getItemSelectable(); if (c.getState()) currstatus="You checked : "; else currstatus="You unchecked : "; currstatus=currstatus+c.getLabel(); ta.setText(currstatus); } } }
Listing 8.12 Using radio buttons

The output of this program would be a set of choices asking for the age from the user and depending on the user input the TextArea would display the appropriate message. Fig. 8.5 shows the output of this program in a browser.

Basic Programming using Java

Event Handling in AWT

Fig. 8.5 Radio Buttons (CheckboxGroup) at runtime

8.5.3

Handling Choices and Lists

The Choice class can be used to create pull-down list objects. These lists are also known as option menus or pop-up menu of choices. The List class is much more sophisticated than the Choice class. It allows the user to select single or multiple items. It displays all these items in a scrollable window from where they can be selected. We will take an example where both of these classes can be implemented and we will see how we can trap the events associated with them.
import java.applet.*; import java.awt.*; import java.awt.event.*; public class Choose extends Applet{ TextField tf; Choice myChoice; List myList[]; int currList=0; String choiceList[]={"Language","Operating Systems", "Database"}; String listList[][]={ {"C","C++","Java","BASIC","COBOL","PASCAL"}, {"DOS","Windows 95","Windows 98","UNIX","LINUX"}, {"Oracle","Sybase","Ingres","DB2"} }; public void init(){ setLayout(new BorderLayout()); tf=new TextField(40); myChoice=new Choice(); for (int i=0;i<choiceList.length;i++){ try{ myChoice.add(choiceList[i]); } catch(NullPointerException ex) { myChoice.add("");} } ChoiceHandler ch=new ChoiceHandler(); myChoice.addItemListener(ch);

Basic Programming using Java

Event Handling in AWT

myList=new List[choiceList.length]; ListHandler lh=new ListHandler(); for (int i=0;i<myList.length;i++){ myList[i]=new List(listList[i].length,true); for (int j=0;j<listList[i].length;j++){ try{ myList[i].add(listList[i][j]); }catch(NullPointerException ex) { myList[i].add("");} } myList[i].addItemListener(lh); } add("North",new Label("Choose the course")); add("South",tf); add("West",myChoice); add("East",myList[currList]); } class ChoiceHandler implements ItemListener{ public void itemStateChanged(ItemEvent e){ for (int i=0;i<choiceList.length;i++) if (choiceList[i].equals(myChoice.getSelectedItem( ))){ Choose.this.remove(myList[currList]); Choose.this.add(myList[i]); currList=i; tf.setText(choiceList[i]); } Choose.this.validate(); } } class ListHandler implements ItemListener{ public void itemStateChanged(ItemEvent e){ String order=myChoice.getSelectedItem()+" : "; String items[]=myList[currList].getSelectedItems(); for (int i=0;i<items.length;i++) order=order+items[i]+" "; tf.setText(order); } } }
Listing 8.13 Implementing Choices and Lists

Basic Programming using Java

Event Handling in AWT

This program listing (listing 8.13) has a Choice item from where one can select Language, Operating Systems or Databases. For each of these choices a popup list appears from where the user can select any one or more of the languages, operating systems or databases. Whatever the user chooses, is shown in a TextField. To create a popup list, an array of List item is taken which will have as many elements as the number of choices. Then for each option in the Choice item, a List item is created. While adding choices and list items with the help of add() method, a NullPointerException is thrown, which is caught in the program and a blank option is added instead. With each List item a ListHandler is associated and with Choice item a ChoiceHandler is associated. Since both Choice and List are items, an ItemListener is implemented with the classes ChoiceHandler and ListHandler. The ItemListener interface has only one method itemStateChanged() which is overridden in each of these classes. The method itemStateChanged() of ChoiceHandler class gets the item selected with the help of getSelectedItem() method. Then it finds the index of this item in the Choice item and makes it the current index. It the removes the current List item from the applet and adds the new list to it. To show the new List item, the validate() method is invoked. The validate() method of Applet class causes a Container like Applet to layout its components again after the components it contains have been added or modified. The TextItem also gets a value, which is the name of the item selected from the Choice item. The method itemStateChanged() of ListHandler class gets the items selected with the help of getSelectedItems() method. The getSelectedItems() method is used when the user selects more than one item from a List. After this, the selected items names are added to the TextItem.

Basic Programming using Java

Event Handling in AWT

Fig. 8.6 shows the output of this program in a browser.

Fig. 8.6 Implementing Lists and Choices

8.5.4

Handling Scrollbars

A Scrollbar is an item that is used to scroll through another item like a Graphics object. The Scrollbar class is used to implement vertical and horizontal scrollbars in Java. A Scrollbar is created by using any one of the three constructor methods of Scrollbar class. The first constructor method takes no argument and is useful when you want to create a Scrollbar and attach the other properties to it later on. The second constructor method takes only one argument (integer type), which represents the orientation of the scrollbar. The Scrollbar class has two constants Scrollbar.HORIZONTAL and Scrollbar.VERTICAL to set the orientation of the Scrollbar. The third constructor takes five integer arguments. The first one represents the orientation of the scrollbar, the second represents the initial value at which the scrollbar would be displayed. The third argument denotes the amount of visible area and fourth and fifth represents the minimum and maximum value. If a vertical scrollbar is to be created for a 100-line text object, the minimum and maximum value would be 0 and 99 and the orientation would be Scrollbar.VERTICAL. If you want to display only 25 lines at a point of time, set visible area as 25. In case of a horizontal scrollbar these values are calculated in pixels. The Scrollbar class has many methods that can be used to manipulate Scrollbar object. The description of some of the important methods is given below:
The getMaximum() and setMaximum(int) methods that can be used to get and set the maximum value of the scrollbar. The getMinimum() and setMinimum(int) methods that can be used to get and set the minimum value of the scollbar.

Basic Programming using Java

Event Handling in AWT

The getOrientation() and setOrientation(int) methods that can be used to get and set the orientation of the scollbar. The getVisibleAmount() and setVisibleAmount(int) methods that can be used to get and set the amount of visible area of the scollbar. The getValue() and setValue(int) methods that can be used to get and set the current value of the scrollbar. The getUnitIncrement() and setUnitIncrement(int) methods that can be used to get and set the increment value when the scrollbar is clicked by mouse or keyboard. The getBlockIncrement() and setBlockIncrement(int) methods that can be used to get and set the increment value when the scrollbar is clicked by mouse or keyboard on the scrollbar area. The setValues(int value, int visible, int minimum, int maximum) method that sets all the four values. The addAdjustmentListener(AdjustmentListener) and removeAdjustmentListener(AdjustmentListener) methods that adds and removes the object that handles the adjustment events.

To understand how a Scrollbar object is created and manipulated, let us create an applet that has a vertical and a horizontal scrollbar attached to it. The applet also has a Label object that displays the current position of the scrollbar whenever the scrollbar is adjusted. The program listing 8.14 given below shows such a program.
import java.applet.*; import java.awt.*; import java.awt.event.*; public class Scroller extends Applet{ Label label=new Label("No change"); MyScrollbar hscroll=new MyScrollbar(Scrollbar.HORIZONTAL,50,10,0,100,label); MyScrollbar vscroll=new MyScrollbar(Scrollbar.VERTICAL,500,100,0,1000,label); public void init(){ setLayout(new BorderLayout()); add("Center",label); add("West",vscroll); add("North",hscroll); } } class MyScrollbar extends Scrollbar{ Label position; String direction="Horizontal"; public MyScrollbar(int orientation,int value,int visible,int min, int max,Label label){ super(orientation,value,visible,min,max); position=label;

Basic Programming using Java

Event Handling in AWT

if (orientation==Scrollbar.VERTICAL) direction="Vertical"; addAdjustmentListener(new ScrollHandler()); } class ScrollHandler implements AdjustmentListener{ public void adjustmentValueChanged(AdjustmentEvent e){ position.setText(direction+" Position : "+e.getValue()); } } }
Listing 8.14 Adding scrollbars to an applet

This program listing shows the creation of a new class called MyScrollbar which is a subclass of Scrollbar class. This class creates a Scrollbar object and attaches an object of ScrollHandler class to it as its AdjustmentListener. The ScrollHandler class implements the AdjustmentListener interface which has only one method called adjustmentValueChanged(). This method finds the current position of the scrollbar using getValue() method of AdjustmentEvent class. It then sets the value of the Label item as the direction and the current value of the scrollbar, which is displayed on the applet screen. There is another method in AdjustmentEvent class called getAdjustmentType() which will return the type of adjustment that caused the value change. The AdjustmentEvent class declares some variables for the convenience of the users to get the type of adjustment events. Some of the important adjustment types are:
AdjustmentEvent.UNIT_INCREMENT AdjustmentEvent.UNIT_DECREMENT AdjustmentEvent.BLOCK_INCREMENT AdjustmentEvent.BLOCK_DECREMENT

Fig. 8.7 shows the output of this program in a browser.

When the horizontal scrollbar is clicked

When the vertical scrollbar is clicked

Fig. 8.7 The Vertical and horizontal scrollbars

8.5.5

Handling Windows, Frames and Dialog boxes

Basic Programming using Java

Event Handling in AWT

Windows are the containers on which the components can be laid out in an application. An application can have many windows. The Window class of java.awt package creates a general Window object. The Window object is a top-level window with no borders and no menubar. A Window object is basically used to implement popup menus. The default layout for Window objects is the BorderLayout. It has two subclasses Frame and Dialog that are used to create main application window and dialog box windows. The Window class has one constructor method that takes a Frame object as an argument, which acts as its parent. This parent frame is necessary since only objects of Frame class or its subclasses have the functionality to implement an independent application window. The Window object has many methods that can be used by Frame and Dialog class objects. Some of the important methods are given below:

The show() method is used to make a window visible. The toBack() method can be used to send a window to back when many windows are open. The toFront() method can be used to bring the window to front when too many windows are open. The dispose() method can be used to free the resources occupied by the window. The pack() method causes sub-components to be laid out at their preferred sizes. The isShowing() method returns a boolean value depending upon the visibility of the window. The addWindowListener(WindowListener) method can be used to add a window listener to it to handle window related events. The removeWindowListener(WindowListener) method can be used to remove the window listener from a window.

8.5.5.1 Frame The Frame class is used to create main window of an application. As said earlier it is a subclass of Window class. A Frame object creates a window that can have a title, a window icon, menu bar and cursor. It is a top-level window that has a title and a border. A Frame window can be opened, closed, minimized, maximized, activated or deactivated. The Frame class has two constructor methods. The first constructor method takes no argument and creates an invisible window with no title. The second constructor takes the window title as an argument and creates an invisible window with that title. Some of the important methods of Frame class are given below:
The getIconImage() method returns represents the icon of that window. The setIconImage(Image) method takes arguments and sets it as the icon of the The getTitle() method returns a represents the title of the window. the Image item that an Image item as an window. String object that

Basic Programming using Java

Event Handling in AWT

The setTitle(String) method takes a String as an argument and sets the title of the window with that. The getMenuBar() method returns the menu bar associated with the frame. The setMenuBar(MenuBar) method sets the MenuBar argument as the frames menu bar.

Let us now create an applet that has two buttons Open Window and Close Window. The Open Window button opens a Frame window and Close Window button closes it. To design this applet, we will first create a subclass of Frame class called MyFrame. The code of MyFrame class is given below (refer to program listing 8.15)

Basic Programming using Java

Event Handling in AWT

import java.awt.*; public class MyFrame extends Frame{ Label l; MyFrame(String title){ super(title); setLayout(new BorderLayout()); l=new Label("This is a test window",Label.CENTER); l.setFont(new Font("TimesRoman",Font.BOLD,28)); add("Center",l); } public Insets getInsets(){ return new Insets(20,0,25,0); } }
Listing 8.15 Creating subclass of Frame class

MyFrame class has one constructor method that takes the title of the window as its argument and sets the window title with that. It has a Label object which is added to the center of the window. This class also leaves a top and bottom margin of 20 and 25 pixels each. This is done with the help of getInsets() method that returns an Insets object. The constructor of Insets class object takes four parameters the top margin, the left margin, the bottom margin, and the right margin. Now we will use an object of this class to create a frame window that will be invoked when the user clicks on to the Open Window button. The program listing 8.16 given below creates such applet.
import java.applet.*; import java.awt.*; import java.awt.event.*; public class FrameWindow extends Applet{ MyFrame window; Button open, close; public void init(){ open=new Button("Open Window"); close=new Button("Close Window"); open.addActionListener(new ButtonHandler1()); close.addActionListener(new ButtonHandler1()); add(open); add(close); window=new MyFrame("My Window"); window.setSize(300,150); window.setLocation(150,200); window.addWindowListener(new WindowHandler1());

Basic Programming using Java

Event Handling in AWT

} class ButtonHandler1 implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if ("Open Window".equals(s)) window.setVisible(true); else if ("Close Window".equals(s)) if (window.isShowing()) window.setVisible(false); } } class WindowHandler1 extends WindowAdapter{ public void windowClosing(WindowEvent e){ window.dispose(); } } }
Listing 8.16 Handling Window Events

This applet creates two Button objects open and close, and a MyFrame object window. It attaches an object of ButtonHandler1 class to each button and adds them to the applet. It also attaches an object of WindowHandler1 class and attaches it to MyFrame object window. It also resizes and relocations the window object with the help of setSize() and setLocation() methods. The ButtonHandler1 class implements ActionListener interface. Its actionPerformed() method gets the action command with the help of getActionCommand() method. If that command is Open Window, it uses the setVisible() method to make the window object visible. It gain uses setVisible() method to close the window in case the action command is Close Window. The WindowHandler1 class extends from WindowAdapter class and handles only one of its methods called windowClosing(). This method is called when a window is being closed down by the system on users request such as clicking the cross button or by choosing the Close option from the windows menu. The dispose() method is called in this method to dispose off the window. Fig. 8.8 shows the output of this applet in a browser.

Basic Programming using Java

Event Handling in AWT

Fig. 8.8 Creating and manipulating Frames

8.5.5.2 Dialog A dialog box is again like a window but its usage is very different from that of a Frame window. A Frame window is used when you want to create the main window of an application. A dialog box, on the other hand, can be used when any information is given to the user or is seeked from the user. For example, when a document is closed in Word, it asks from the user if he wishes to save the file or not. The window that contains this message is a dialog box. Basically, dialog box is meant for interaction between the user and the system. A dialog box can either be modal or modeless. If a dialog box is modal, the user cannot resume his working with the other applications till he responds to that dialog box. A modeless dialog box, on the other hand, lets a user switch between itself and the other window applications. In Java a dialog box is implemented by creating an object of Dialog class or by creating a subclass of it and then using that to design dialog box applications. We will use the second method in our examples since that way more functionality can be added to a dialog box. The Dialog class has four constructor methods. The first method takes only one argument, i.e., the parent frame of the dialog box. The second constructor takes two arguments the parent frame and a boolean value indicating the modality of the window. The third constructor again takes two arguments the parent frame and the window title. The fourth constructor method takes three arguments the parent frame, the title of the dialog box and the modality flag. The important methods of Dialog class are given below:
The setTitle(String) method sets the title of the window. The getTitle() method returns the title of the window.

Basic Programming using Java

Event Handling in AWT

The isResizable() method returns a boolean value indicating whether the dialog box is resizable or not. The setResizable(boolean) method sets the resizable flag. The isModal() method returns a boolean value indicating the modality of the dialog box. The setModal(boolean) method sets the modality of the dialog box. The show() method makes the dialog box visible.

Refer to the program that created a frame window with a label placed in its center. We will modify that application so that the frame window also has a button called Set Text, which will invoke the dialog window when clicked. The Dialog window will have a TextField and a Button object called OK. The label of the Frame window is set with the text in the TextField when the user clicks on to the OK button. To implement such a thing, we will create a subclass of Frame class called MyFrame1, which will contain a Label item and a Button item called Set Text. Program listing 8.17 given below creates MyFrame1 class.
import java.awt.*; import java.awt.event.*; public class MyFrame1 extends Frame{ Label l; String message="This is a test window"; MyDialog dl; MyFrame1(String title){ super(title); setLayout(new BorderLayout()); l=new Label(message,Label.CENTER); l.setFont(new Font("TimesRoman",Font.BOLD,28)); add("Center",l); dl=new MyDialog(this,"Enter Text",true); dl.setSize(150,150); dl.setLocation(150,300); Button b=new Button("Set Text"); b.addActionListener(new ButtonHandler3()); add("South",b); } public Insets getInsets(){ return new Insets(20,0,25,0); } class ButtonHandler3 implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if ("Set Text".equals(s)) dl.setVisible(true); } } }
Listing 8.17 Creating the MyFrame1 class

Basic Programming using Java

Event Handling in AWT

The MyFrame1 class has three variables a Label item that is displayed at the center of the frame, a String object that hold the message to be displayed by the Label item, and an object of MyDialog class. MyDialog class is a subclass of Dialog class, refer to program listing 8. to see its internal working. The constructor method of this class accepts a title and sets the title of the frame with that value. It also creates an object of MyDialog class and resizes and repositions it. The button having the label Set Text is also created and placed in the frame window. The button has an object of ButtonHandler3 class attached to it to trap the button click event. When this button is clicked the dialog box is shown on the screen. Let us now see the code of MyDialog class (refer to listing 8.18).
import java.awt.*; import java.awt.event.*; public class MyDialog extends Dialog{ TextField tf; MyFrame1 DFrame; MyDialog(Frame parent, String title, boolean modal){ super(parent,title,modal); DFrame=(MyFrame1)parent; setLayout(new BorderLayout(10,10)); tf=new TextField("A test dialog box",30); add("Center",tf); Button b= new Button("OK"); b.addActionListener(new ButtonHandler2()); add("South",b); } class ButtonHandler2 implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if (s.equals("OK")){ setVisible(false); DFrame.l.setText(tf.getText()); } } } }
Listing 8.18 MyDialog class

The MyDialog class has a TextField in which it accepts the text from the user with which it sets the label of the frame window. It has a constructor method that accepts an object reference to the frame for which the text has to be changed, the title of the dialog box and the modality flag of the dialog box. It calls the constructor method of the super class to create the dialog box and attaches the TextField object and a Button object to it. The Button object has a ButtonHandler attached to it that sets the Label item of the frame object with the value in TextField and sets the visible property of the dialog box to false.

Basic Programming using Java

Event Handling in AWT

Now we will create an applet that has two buttons Open Window and Close Window. The program listing 8.19 given below does this.
import java.applet.*; import java.awt.*; import java.awt.event.*; public class DialogWindow extends Applet{ MyFrame1 window; Button open, close; public void init(){ open=new Button("Open Window"); close=new Button("Close Window"); open.addActionListener(new ButtonHandler1()); close.addActionListener(new ButtonHandler1()); add(open); add(close); window=new MyFrame1("My Window"); window.setSize(300,150); window.setLocation(150,200); window.addWindowListener(new WindowHandler1()); } class ButtonHandler1 implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if ("Open Window".equals(s)) window.setVisible(true); else if ("Close Window".equals(s)) if (window.isShowing()) window.setVisible(false); } } class WindowHandler1 extends WindowAdapter{ public void windowClosing(WindowEvent e){ window.dispose(); } } }
Listing 8.19 Creating an applet that utilizes both frames and Dialog boxes

Basic Programming using Java

Event Handling in AWT

This program listing is exactly the same as in case of Frames (refer to program listing 8.16) with the only difference being that an object of MyFrame1 class is used instead of MyFrame class. The output of this program is given below (refer to fig.8.9).

Fig. 8.9 Browser showing a dialog window and a frame window

8.5.6

Case StudyCollege Student Enrolment System (Contd.)

In the previous session we saw how to make the GUI for opening screen without any event handling. We will now expand the same program to handle events for button button1.
import import import import java.awt.*; java.awt.event.*; java.applet.*; java.net.URL;

public class SInterface extends Applet { Panel panel2 = new Panel(); Label label1 = new Label(); TextArea textArea1 = new TextArea(); Button button1 = new Button(); Panel panel1 = new Panel(); //Construct the applet public SInterface() { } //Initialize the applet

Basic Programming using Java

Event Handling in AWT

public void init() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } //Component initialization private void jbInit() throws Exception { resize(400,300); setLayout (null); panel2.setBackground(new Color(255, 192, 114)); label1.setFont(new Font("Dialog", 1, 20)); label1.setText("Student Enrollment System"); textArea1.setBackground(Color.white); textArea1.setText("Tulec Enrollment system currently offers courses on ..."); textArea1.setEditable(false); button1.setLabel("Select Courses"); button1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { button1_actionPerformed(e); } }); panel1.setBackground(new Color(191, 192, 117)); panel1.setForeground(new Color(72, 0, 0)); panel1.setBounds(1, 1, 89, 298); this.add(panel1); panel2.setBounds(90, 1, 309, 86); this.add(panel2); panel2.add(label1); textArea1.setBounds(92, 90, 50, 50); this.add(textArea1); button1.setBounds(2, 81, 50, 50); panel1.add(button1); } void button1_actionPerformed(ActionEvent e) { AppletContext ac = getAppletContext(); URL url; try{ url= new URL(getCodeBase()+"GCInterface.html"); ac.showDocument(url); }catch(java.net.MalformedURLException e1){

Basic Programming using Java

Event Handling in AWT

showStatus("URL not found"); } } }


Listing 8.20 Handling events in the opening screen of Case Study

As seen in the code above actionListener is attached to the button button1. When user clicks on button button1 , method button1_actionPerformed is called. Here we get the AppletContext of the current applet by method getAppletContext(). The AppletContext is an interface that lets you get information from the applets execution environment. Using the AppletContexts showDocument(URL) method we call on another html document in the same window. The statement url = new URL (getCodeBase()+ GCInterface.html) will form URL for the path in which our called document GCInterface.html is located. If the URL is invalid then in the exception code it displays URL not found message on the status bar of the browser.

AppletContext falls into two categories: methods that provide access to other applets running in the same context, and methods that allow interaction with the browser itself. The methods that access other applets are getApplet() and getApplets(). Applet interaction with the web browser is provided by the remaining methods of the AppletContext, showStatus() and showDocument() are two such methods. The showStatus() can be used to display message strings in the status area that browsers may provide. Since providing a textual status area is an independent decision, some browser vendors implement it, some dont. Hence using showStatus() for displaying critical messages is always discouraged.

We continue with another class ChangedField which implements Keyboard Listener. This class facilitates the entry validations for textfield components. In the subsequent programs ChangedField has been used to validate only one textfield but that is to give the user an idea of how it can be used. The user can further use it for validating all other textfields.
package college.student; import import import import import java.awt.TextField; java.awt.event.KeyListener; java.awt.event.KeyEvent; java.awt.Component; java.awt.event.InputEvent;

public class ChangedField extends TextField implements KeyListener { //sets digits as valid key inputs public static final int DIGITS = 1;

Basic Programming using Java

Event Handling in AWT

//sets alphabets as valid key inputs public static final int ALPHA = 2; //sets function keys as valid key inputs public static final int F_KEYS = 4; //sets special keys as valid key inputs public static final int PERIOD = 8; //member variable to hold the valid key inputs private int iValidKeyCode; //maximum number of characters private int iMaxChar; public ChangedField() { super(); iValidKeyCode = 15; iMaxChar = -1; addKeyListener(this); } // sets the maximum no of characters indicates any no. of chars. // which is the default setting). public void setMaxChars(int iMaximum) { iMaxChar = iMaximum; } // Assign the value of valid key code groups to member variable public void setValidKeys(int iValidKeyArg){ iValidKeyCode = iValidKeyArg; } public void keyPressed(KeyEvent keEvent){ //gets the keycode of the key pressed int iKeyPressedCode = keEvent.getKeyCode(); int iModifiers = keEvent.getModifiers(); //checks whether key input is a system key if((iKeyPressedCode == KeyEvent.VK_BACK_SPACE) || (iKeyPressedCode == KeyEvent.VK_END)|| (iKeyPressedCode == KeyEvent.VK_SPACE)|| (iKeyPressedCode == KeyEvent.VK_LEFT)|| (iKeyPressedCode == KeyEvent.VK_RIGHT)|| (iKeyPressedCode == KeyEvent.VK_ESCAPE)|| (iKeyPressedCode == KeyEvent.VK_HOME)|| (iKeyPressedCode == KeyEvent.VK_DELETE)|| (iKeyPressedCode == KeyEvent.VK_TAB)|| (iModifiers == InputEvent.ALT_MASK)||

to

be

entered.(-ve

Basic Programming using Java

Event Handling in AWT

(iModifiers == InputEvent.CTRL_MASK)) return; if((iMaxChar > 0) && (getText().length() >= iMaxChar)) keEvent.consume(); //checks whether key input is a digit if((iValidKeyCode & 1) == 1) if((iKeyPressedCode >= KeyEvent.VK_0 && iKeyPressedCode<= KeyEvent.VK_9) && (!(keEvent.isShiftDown()))) return; //checks whether key input is an alphabet if((iValidKeyCode & 2) == 2) if((iKeyPressedCode >= KeyEvent.VK_A && iKeyPressedCode <= KeyEvent.VK_Z)) return; //checks whether key input is a function key if((iValidKeyCode & 4) == 4) if((iKeyPressedCode >= KeyEvent.VK_F1 && iKeyPressedCode<= KeyEvent.VK_F12)) return; //checks whether key input is a special key if((iValidKeyCode & 8) == 8) if(keEvent.getKeyChar() == '.') return;

//if the key input is invalid consume the event keEvent.consume(); }

public void keyReleased(KeyEvent keEvent){ } public void keyTyped(KeyEvent keEvent){ } }


Listing 8.21 Handling key events in a textfield

The method keyPressed of KeyListener gets the keycode of the key pressed, checks whether it belongs to a valid key group according to the value of the member variable iValidKeyCode. If it is valid ,it appends the character to the textfield. If it is not valid, the key pressed event is ignored. Method setMaxChars(int) sets the maximum number of characters to be entered. Method setValidKeys(int) sets the type of keys, which can be accepted by the field. Method keyEvent.consume() consumes the event, that is, the

Basic Programming using Java

Event Handling in AWT

event is simply ignored. To use this class you simply create an object of ChangedField class. For displaying error messages in the applet, which handles the enrolment system we will use the class CreateOkDialog.
package college.student; import java.awt.*; import java.awt.event.*; class MyDialog extends Dialog{ Label lblMessage; MyDialog(Frame parent,String title,boolean modal,String mess){ super(parent,title,modal); setLayout(new BorderLayout(10,10)); lblMessage=new Label(mess); setSize(150,150); setLocation(150,300); add("Center",lblMessage); Button b= new Button("OK"); b.addActionListener(new ButtonHandler2()); add("South",b); } class ButtonHandler2 implements ActionListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if (s.equals("OK")){ setVisible(false); } } } } public class CreateOkDialog extends Frame{ CreateOkDialog(String message){ MyDialog dlg = new MyDialog(this,"Message ",true,message); dlg.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ dispose(); } } ); dlg.show(); } }
Listing 8.22 Creation of dialog box for displaying error messages

In the listing given above MyDialog class creates a dialog window for displaying messages passed to it as a string. It has Ok button which has an associated action handler. This class gets instantiated in CreateOkDialog class, to which required

Basic Programming using Java

Event Handling in AWT

parameters are passed. The dialog object is also associated with a WindowListener, this listener implements closing of dialog window when X button is clicked. 8.5.7 Handling Menus

A menu is an important part of any application. A menu gives the user a list of choices. A menu consists of a menu bar and the menu items. For example, in MS-Word, the bar that contains the menu items like File, Edit, View, Insert, etc. is the menu bar. A menu item can have many sub-items also, for example, File menu item has sub-items as New, Open, Close, Save, etc. Java API has a lot of menu related classes that can be used to create menus. The MenuComponent is the main class from where the subclasses required to create a complete menu are created. MenuComponent is a subclass of Object class. MenuBar and MenuItem are the two subclasses of MenuComponent class that are used to create menu bar and menu items respectively. MenuItem is again subclassed into CheckboxMenuItem and Menu classes. A CheckboxMenuItem class is used to create checkbox menu items. These are the items that have a tick against them, for example, in Word Ruler submenu item of View menu item is a checkbox item. Menu class can be used to create a collection of menu items. Another class called PopupMenu is a subclass of Menu that can be used to create popup menus. MenuShortcut class, which is a subclass of Object, can be used to create menu shortcuts. These shortcuts can then be attached to menu items. Fig. 8.10 given below shows the hierarchy of all menu related classes.
Object

MenuComponent

MenuShortcut

MenuBar

MenuItem

CheckboxMenuItem

Menu

PopupMenu

Fig. 8.10 Hierarchy of menu related classes

To create a menu, a menu bar is created first and then items are attached to it. A menu bar is then attached to a Frame window. A menu item can be of the following types: A disabled normal menu item An enabled normal menu item

Basic Programming using Java

Event Handling in AWT

A disabled checkbox item that has been checked in the beginning An enabled checkbox item that has been checked in the beginning A disabled checkbox item that has been unchecked in the beginning An enabled checkbox item that has been unchecked in the beginning

We will create a menu that will have each of these types of items. Let us first start with the creation of a menu that will contain one or more items. MenuItem class can be used to create a menu item. There are three constructor methods for MenuItem class. The first constructor takes no argument and creates a new menu item. The second constructor takes a String argument and creates a menu item with the label represented by the String object. The third constructor takes two arguments a String name that represents the label of menu item and a MenuShortcut item. It then attaches that shortcut to the new menu item created. Some of the important methods of MenuItem class are given below::
The addActionListener() method of MenuItem class can be used to attach an ActionListener to the menu item. The removeActionListener(ActionListener) method can be used to remove an ActionListener. The getActionCommand() method can be used to get the command name of the action event that is fired by this menu item. The setActionCommand(String) method is used to set the command name that is fired by this event. The getLabel() method is used to get the label of the menu item. The setLabel(String) method is used to set the label of menu item. The isEnabled() method is used to check if this menu item is enabled. The setEnabled(Boolean) method is used to set the enabled flag of this menu item. The getShortcut() method is used to get the MenuShortcut item associated with this menu item. The setShortcut(MenuShortcut) is used to set the shortcut for this menu item.

A menu is nothing but a collection of menu items. You can create a menu either by using Menu class directly or by extending Menu class to create your own class and then creating an object of that class. The second way is more effective than the first one, since that way you can attach your own functionalities to the menu. The Menu class has three constructor methods. The first constructor takes no argument, the second takes the menu label as an argument and third one takes a menu label and a boolean value that decides whether this menu is a tear-off menu or not. Some of the important methods of Menu class are given below:
The method add(MenuItem) adds a specific menu item to this menu. The method add(String) adds an item with this label to the menu. The method remove(int) removes a menu item at the specified index position.

Basic Programming using Java

Event Handling in AWT

The method remove(MenuComponent) removes a specific menu component from this menu. The method removeAll() removes all menu items from this menu. The method addSeparator() adds a separator to the menu. The method insertSeparator(int) adds a separator to the menu at the specified index position. The method insert(MenuItem,int) inserts a MenuItem at the specified index position. The method insert(String,int) inserts an item at the specified index position. The method getItem(int) gets the menu item at the specified index position. The methos getItemCount() gets the total number of items in this menu.

Now that we know about the Menu and MenuItem class, let us create a MyMenu class that will accept have only one constructor method and one method called getItem(String) that will return the menu item that has the label same as the one represented by that String object. The constructor method accepts three arguments. The first argument is an array of items of Object class. It creates a menu item from the first element of this array and makes the rest of the elements as its sub-items. While creating a menu item, it keeps the following things in mind. If the first character of the label name is a ~, it creates a disabled MenuItem. +, it creates an enabled checked CheckboxMenuItem. #, it creates a disabled checked CheckboxMenuItem. -, it creates an enabled unchecked CheckboxMenuItem. =, it creates a disabled unchecked CheckboxMenuItem. Otherwise it creates a normal MenuItem. A CheckboxMenuItem needs an ItemListener and a normal MenuItem needs an ActionListener to trap the menu events. Therefore the constructor accepts both an object of ActionListener type and an object of ItemListener type. It then attaches either of these to the menu items depending on whether they are normal items or checkbox menu items. Program listing 8.23 shows the code for MyMenu class.
import import public public java.awt.*; java.awt.event.*; class MyMenu extends Menu{ MyMenu(Object labels[],ActionListener al,ItemListener il){ super((String)labels[0]); String menuName=(String)labels[0]; char firstChar=menuName.charAt(0); if (firstChar=='~'){ setLabel(menuName.substring(1)); setEnabled(false); } else setLabel(menuName); for (int i=1;i<labels.length;i++){ if (labels[i] instanceof String){

Basic Programming using Java

Event Handling in AWT

if (labels[i].equals("-")) addSeparator(); else { String name=(String)labels[i]; firstChar=name.charAt(0); switch(firstChar){ case '+' : CheckboxMenuItem ci=new CheckboxMenuItem(name.substring(1)); ci.setState(true); add(ci); ci.addItemListener(il); break; case '#': ci=new CheckboxMenuItem(name.substring(1)); ci.setState(true); ci.setEnabled(false); add(ci); ci.addItemListener(il); break; case '-' : ci=new CheckboxMenuItem(name.substring(1)); ci.setState(false); add(ci); ci.addItemListener(il); break; case '=' : ci=new CheckboxMenuItem(name.substring(1)); ci.setState(false); ci.setEnabled(false); add(ci); ci.addItemListener(il); break; case '~' : MenuItem mi=new MenuItem(name.substring(1)); mi.setEnabled(false); add(mi); mi.addActionListener(al); break; default : mi=new MenuItem(name); add(mi); mi.addActionListener(al); } } } else add(new MyMenu((Object[])labels[i],al,il)); } } public MenuItem getItem(String mi){

Basic Programming using Java

Event Handling in AWT

int n=getItemCount(); for (int i=0;i<n;i++) if (mi.equals(getItem(i).getLabel())) return getItem(i); return null; } }
Listing 8.23 Creating MyMenu class

Using this class menus can be created easily. Now we will create a menu bar that will hold these menus together. The MenuBar class can be used to create a menu bar. This class has only one constructor that takes no argument. Some of the important methods of this class are given below:
The add(Menu) method adds a specific menu to this menu bar. The remove(Menu) method removes a specific menu from this menu bar. The remove(int) method removes a menu at the specified index position in this menu bar. The getMenu(int) method gets the Menu at the specified index position. The getMenuCount() method returns the total number of menus in this menu bar. The getShortcutMenuItem(MenuShortcut) method returns the menu item that has the specified shortcut. The deleteShortcut(MenuShortcut) method deletes the specified menu shortcut.

Let us now create a class called MyMenuBar, which extends from the MenuBar class. This class has only one constructor method, which accepts a two-dimensional array of Objects, an ItemListener and an ActionListener. It creates a menu bar and attaches the menus represented by the two-dimensional array. It uses MyMenu class to create the menus. It also has a method called getItem(String) that returns the MyMenu item represented by that String. The code of this class is given below (refer to program listing 8.24).
import java.awt.*; import java.awt.event.*; public class MyMenuBar extends MenuBar{ public MyMenuBar(Object labels[][],ActionListener al, ItemListener il) { super(); for (int i=0;i<labels.length;i++) add(new MyMenu(labels[i],al,il)); } public MyMenu getMenu(String name){ int n=getMenuCount(); for (int i=0;i<n;i++) if (name.equals(getMenu(i).getLabel())) return ((MyMenu)getMenu(i)); return null;

Basic Programming using Java

Event Handling in AWT

} }
Listing 8.24 The MyMenuBar class

The next step is now to attach this menu bar to a frame. Listing 8.25 shows the code that creates a class called MenuFrame that is a subclass of Frame class. This class creates a menu with different items. Some of these items are checkbox items, some are disabled, and some are normal items. It also has a Label object that gets updated as soon as any of the menu item is clicked. Whenever a menu item is clicked it generates an ActionEvent or an ItemEvent depending on whether it is a normal menu item or a checkbox menu item.
import java.awt.*; import java.awt.event.*; public class MenuFrame extends Frame{ MyMenuBar mbar; JobHandler jb=new JobHandler(); Label l; public MenuFrame(){ super("Presenting Menus"); setup(); setSize(400,300); addWindowListener(new WindowHandler3()); setVisible(true); l=new Label(""); l.setFont(new Font("Tahoma",Font.BOLD,24)); add("Center",l); } void setup(){ setBackground(Color.yellow); String gotoMenu[]={"Start","End","-","Line No."}; Object mitems[][]={ {"File","New","Open","~Save","-","~Close","","~Print","-","Exit"}, {"Search","Find","~Find Next","~Find Previous, "-", gotoMenu}, {"View","-Page Layout","+Normal","+Line No."}, {"Help","About Us"} }; mbar=new MyMenuBar(mitems,jb,jb); setMenuBar(mbar); } class JobHandler implements ActionListener,ItemListener{ public void actionPerformed(ActionEvent e){ String s=e.getActionCommand(); if ("Exit".equals(s)) System.exit(0); else { if ("New".equals(s) || "Open".equals(s)){ mbar.getMenu("File").getItem("Save").setEnabled(true);

Basic Programming using Java

Event Handling in AWT

mbar.getMenu("File").getItem("Close").setEnabled(true); mbar.getMenu("File").getItem("Print").setEnabled(true); } else if ("Find".equals(s)){ mbar.getMenu("Search").getItem("Find Next").setEnabled(true); mbar.getMenu("Search").getItem("Find Previous").setEnabled(true); } } l.setText("Your choice: "+s); validate(); } public void itemStateChanged(ItemEvent e){ l.setText("Your choice: "+e.getItem()); validate(); } } class WindowHandler3 extends WindowAdapter{ public void windowClosing(WindowEvent e){ dispose(); System.exit(0); } } }
Listing 8.25 The MenuFrame class

The frame that is created is resized and is made visible after the menu bar with all the menu items has been attached to it. A Window Handler is also added to it so that it can trap relevant window events. When the window is closed down, it disposes itself and comes out of the Java program. A JobHandler class is also created that implements both ActionListener and ItemListener and thus overrides both actionPerformed() and itemStateChanged() methods. In both of these methods the Label item is reset with the label name of the current item. The validate() method causes the frame components to be laid down again or in other words, it refreshes the frame window so that the Label object displays the current menu item label. In actionPerformed() method, the Save, Close and Print items are enabled if the menu item clicked is either New or Open. Similarly Find Next and Find Previous menu items are enabled if the Find item is clicked. To be able to create a Frame using MenuFrame class, the following code can be written:
public class TestMenu{ public static void main(String args[]){ MenuFrame mf=new MenuFrame(); } }
Listing 8.26 Creating TestMenu class

This file can then be compiled and run. Fig. 8.11 shows the output of this program code.

Basic Programming using Java

Event Handling in AWT

Menu having submenu items

Menu in the beginning

Menu after clicking on the New option

Basic Programming using Java

Event Handling in AWT

Checkbox menu in the beginning

Checkbox menu after clicking Page Layout

Fig. 8.11 TestMenu application running

Basic Programming using Java

Event Handling in AWT

SUMMARY
The java.awt package lets you create various components like buttons, checkboxes, scrollbars, etc. The java.awt.event package contains classes that let you handle the user response to these components. An event is generated in response to anything that a user does when a program is running like clicking of the mouse, hitting a key, checking a checkbox, etc. Events broadly fall in four categories mouse click events, mouse motion events, keyboard events, and user-interface events. Java 1.2 model uses Listener-Adapter model to handle events. Different types of events use different types of listeners or adapters to handle events. Listeners are interfaces that have a set of methods that can be used handle various types of events. In case a Listener is used, you must override all the methods in that Listener. Adapters are classes that can be used in place to Listeners if only a few methods have to be overridden. To handle mouse clicks, MouseListener interface or MouseAdapter class can be used. To handle mouse movements, MouseMotionAdapter class can be used. MouseMotionListener interface or

To handle keyboard events, KeyListener interface or KeyAdapter class can be used. Components like Buttons can use ActionListener interface that has only one method called actionPerformed() that has to be overridden. Components like Checkboxes, CheckboxGroups, Lists, Choices, etc, can use ItemListener interface that has only one method called itemStateChanged() that needs to be overridden. Scrollbar component can use AdjustmentListener interface or AdjustmentAdapter class to handle scrollbar events. Windows, Frames and Dialog boxes can use WindowListener interface or WindowAdapter class to handle events like closing of a window, opening of a window, activating a window, etc. MenuBar component is attached to a Frame. MenuItem components can use ActionListener interface to handle menu-clicked events.

You might also like