16 Working with AWT

16.1 INTRODUCTION TO AWT

AWT stands for Abstract Window Toolkit. The toolkit is defined within the java.awt package. It contains all of the classes for creating user interfaces like Buttons, Labels, TextBox, Lists, etc., and for painting graphics and images. The AWT provides many classes for programmers to use. It is the connection between an application and the native GUI. The AWT hides the system from the underlying details of the GUI, the application will be running on and thus is at very high level of the abstraction. All of the classes are arranged in a meaningful hierarchy so that many of the features of the top-most classes can be used in a number of subclasses.

16.2 STRUCTURE OF THE AWT

The structure of the AWT is rather simple: Components are added to and then laid out by layout managers in Containers. There is a variety of event handling, menu, fonts and graphics classes in addition to the above two. The hierarchy of AWT classes is as shown below:

images BorderLayout

images CheckboxGroup

images Color

images Component

• Button

• Canvas

• Checkbox

• Choice

• Container

images Panel

images Window

images Dialog

images Frame

• Label

• List

• Scrollbar

• TextComponent

images TextArea

images TextField

images Dimension

images Event

images FileDialog

images FlowLayout

images Font

images FontMatrics

images Graphics

images GridLayout

images GridBagConstraints

images GridbagLayout

images Image

images Insets

images Media Tracker

images MenuComponent

• MenuBar

• MenuItem

images CheckboxMenuItem

images Menu

images Point

images Polygon

images Rectangle

images Toolkit

Most commonly used classes and their brief description of AWT are given below:

Class Description
AWTEvent The root event class for all AWT events.
BorderLayout Lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west and centre.
Button Creates a push-button control.
Canvas A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.
CardLayout A CardLayout object is a layout manger for a container. Card layouts emulate index cards. Only the one on top is showing.
Checkbox A graphical component that can be in either an "on" (true) or "off" (false) state.
CheckboxGroup The CheckboxGroup class is used to group together a set of Checkbox buttons.
CheckBoxMenuItem This class represents a check box that can be included in a menu.
Choice The Choice class presents a pop-up menu of choices.
Color The Color class is used to encapsulate colors in the default RGB color space.
Component An object having a graphical representation that can be displayed on the screen and that can interact with the user.
Container A generic AWT container object is a component that can contain other AWT components.
Cursor A class to encapsulate the bitmap representation of the mouse cursor.
Dialog A top-level window with a title and a border that is typically used to take some form of input from the user.
Dimension The Dimension class encapsulates the width and height of a component (in integer precision) in a single object.
FileDialog The FileDialog class displays a dialog window from which the user can select a file.
FlowLayout Arranges components in a directional flow, much like lines of text in a paragraph.
Font The Font class represents fonts, which are used to render text in a visible way.
FontMetrics The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.
Frame A top-level window with a title and a border.
Graphics Encapsulates the graphics context. This context is used by the various output methods to display output in a window.
Graphics2D The Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management and text layout.
GraphicsEnvironment The GraphicsEnvironment class describes the collection of GraphicsDevice objects and Font objects available to a Javaâ„¢ application on a particular platform.
GridBagLayout The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size.
GridLayout The GridLayout class is a layout manager that lays out a container's components in rectangular grid.
Image The abstract class Image is the superclass of all classes that represent graphical images.
Insets An Insets object is a representation of the borders of a container.
Label A Label object is a component for placing text in a container.
List The List component presents the user with a scrolling list of text items.
MediaTracker The MediaTracker class is a utility class to track the status of a number of media objects.
Menu A Menu object is a pull-down menu component that is deployed from a menu bar.
MenuBar The MenuBar class encapsulates the platform's concept of a menu bar bound to a frame.
MenuItem All items in a menu must belong to the class MenuItem, or one of its subclass.
MenuShortcut The MenuShortcut class represents a keyboard accelerator for a MenuItem.
Panel Panel is the simplest container class.
Point Encapsulates a Cartesian coordinate pair, stored in x and y.
Polygon The Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space.
PopupMenu A class that implements a menu which can be dynamically popped up at a specified position within a component.
Rectangle Specifies an area in a coordinate space that is enclosed by the Rectangle object's top-left point (x, y) in the coordinate space, its width and its height.
Scrollbar The Scrollbar class embodies a scroll bar, a familiar user-interface object.
ScrollPane A container class which implements automatic horizontal and/or vertical scrolling for a single child component.
SystemColor A class to encapsulate symbolic colors representing the color of native GUI objects on a system.
TextArea A TextArea object is a multi-line region that displays text.
TextField A TextField object is a text component that allows for the editing of a single line of text.
Toolkit This class is the abstract superclass of all actual implementations of the AWT.
Window A Window object is a top-level window with no border and no menu bar.

Table 16.1 Classes defined by java.awt package

16.3 AWT WINDOW HIERARCHY

The AWT window hierarchy is shown by the in Figure 16.1 diagram.

All of the classes are discussed in the following sections.

16.3.1 The Component Class

images

Figure 16.1 AWT window hierarchy

A component is an object having a graphical representation that can be displayed on the screen and interact with the user. Examples of components are the buttons, checkboxes and scrollbars of a typical graphical user interface. In other words the visible User Interface (UI) controls that the user interacts with all of which have been added to a Container are components. Anything that is derived from the class Component can be a component. The class contains a number of useful methods for event handling, managing graphics painting and sizing and resizing the window. This class is the topmost class in the AWT hierarchy. The Component class is the abstract superclass of the non-menu-related AWT components.

16.3.2 The Container Class

A generic AWT container object is a component that can contain other AWT components. The Container class is the subclass of the Component class. Components added to a container are tracked in a list. The order of the list will define the component's font-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list.

Containers (Frames, Dialogs, Windows and Panels) can contain components and are themselves components, hence can be added to Containers. Containers usually handle events that occurred to the Component, but the code for handling events can be written in the component, too. A container is responsible for laying out (i.e., positioning) any components that it contains. It does this through the use of various layout mangers that are discussed later in Chapter 17.

Every Container is a component since it is derived from Component; thus it can also behave and be used like a Component. All of the methods in Component can be used in a Container. Container has two direct subclasses, Window and Panel. They are discussed below.

16.3.3 The Panel Class

Panel is the simplest container class because Container class is the superclass for Panel class. A panel provides space in which an application can attach any other component, including other panels. A Panel is a container that does not exist independently. The Applet class is a subclass of Panel, and as has been seen, as applet does not exist on its own; it must be displayed on a Web page or in some other window. Any panel must be contained inside something else, either a Window, another Panel, or in the case of an Applet, a page in a Web browser. It means that a Panel is a window that contains no title bar, menu bar or border. Due to this, when an applet is run inside a Web browser no title, border or menu is displayed. A simple plain rectangular region is displayed. In case of running, applet using appletviewer, the appletviewer application provides the above-mentioned border, title and menus.

The component can be added to the Panel using add method as will be seen in the programs following. A number of methods defined by Component class like setSize, SetBounds and setTitle can be used for changing their shape and look. The fact that panels can contain other panels means that one can have many levels of components containing other components.

16.3.4 The Window Class

A Window objects is a top-level window with no borders and no menu bar. A Window represents an independent to-level window that is not contained in any component. Window is not really meant to be used directly. It has two subclasses: Frame, to represent ordinary windows that can have their own bars, and Dialog to represent dialog boxes that are used for limited interactions with the user.

16.3.5 The Frame Class

Applets are a fine idea. It is nice to be able to put a complete program in a rectangle on a Web page. But more serious, large-scale programs have to run in their own window, independently of a Web browser. In Java, a program can open an independent window by creating an object of type Frame. A Frame has a title, displayed in the title bar at the top of the window. It can have a menu bar containing one or more pull-down menus. A Frame is a Container, which means that it can hold other GUI components. The default layout manager for a frame is a BorderLayout. A common way to design a frame is to add a single GUI component, such as a Panel or Canvas, in the layout's center position so that it will fill the entire frame.

It is possible for an applet to create a frame. The frame will be a separate window from the Web browser window in which the applet is running. Any frame created by an applet includes a warning message such as "Warning: Insecure Applet Window". The warning is there so that one can always recognize window created by applets. When a Frame window is created by a program rather than an applet, a normal window is created.

16.3.6 Applet Frame Class

The Frame class you will use to create child window's of an applet window. The class defines the following two commonly used constructors.

1.   public Frame()

This form of constructor constructs a new instance of Frame that is initially invisible. The title of the Frame is empty.

2.   public Frame(String title)

This form of constructor creates a new, initially invisible Frame object with the specified title.

The useful methods of Frame class are discussed below:

images setSize() method

This method is used for setting the dimensions of the frame window. The method has two forms:

   void setSize(int w, int h)
   void setSize(Dimension d)

In the first form, the width and height are specified by w and h in terms of pixels. In the second object, a dimension object d is passed that contains width and height of the frame window.

images getSize()method

This method returns the dimension of the frame window as Dimension object. Its signature is given below:

   Dimension getSize()

images setVisible()method

This frame window after creation is invisible. To make it visible the setVisible method can be used. It has the following form:

   void setVisible(boolean flag)

If the flag is true frame window will be visible else, it will be invisible.

images setTitle() method

This method can be used for setting the title of the frame window. It has the following form:

   void setTitle(String title)

images getTitle()method

   String getTitle()

This method returns the title of the frame. The title is displayed in the frame's border.

images setResizeable()method

The signature of the method is given below:

   void setResizable(boolean rs)

This method sets whether this frame is resizable by the user. If rs is false, the frame window cannot be resized. By default, the frame is resizable.

Some other methods will be demonstrated programmatically.

The frame class can receive the following events:

• WINDOW_OPENED

• WINDOW_CLOSING

• WINDOW_CLOSED

• WINDOW_ICONIFIED

• WINDOW_DEICONIFIED

• WINDOW_ACTIVATED

• WINDOW_DEATIVATED

• WINDOW_GAINED_FOCUS

• WINDOW_LOST_FOCUS

• WINDOW_STATE_CHANGED

One important point to note while working with frame window is that frame window cannot be closed manually by clicking at the close button. In case frame window is created by the applet window, frame window will be closed automatically as the applet window is closed. But in case frame window is created by simple application program, it cannot be closed. For both the cases the event handling code can be written. For closing the window the windowClosing method of WindowListener interface will be written for removing the window from the screen.

Now, a few programs are presented that give an idea on how to work with Frame class. A Frame can be created inside an applet or an application program. The applications programs of Frame are first presented. Subsequently, some Frame-based applets will be dealt with.

/*PROG 16.1 CREATING YOUR FIRST FRAME WINDOW */
import java.awt.*;
class tem1
{
      public static void main(String[] args)
      {
             Frame F = new Frame("This is My First Frame");
             F.setSize(200, 200);
             F.setVisible(true);
      }
}

Explanation: The program is very simple. A new Frame instance is created by the name F and with title "This is My First Frame". The size of the new frame window is 200 by 200. The window is made visible by using setVisible method. Note that after the frame window is created, it cannot be destroyed by clicking the close button. It will have to be closed forcibly by using command Ctrl-C under window or explicitly closing editor output window, in case some Java editor is used for running the programs. Note the program is a simple application program, and not an applet.

In general, the Frame class is extended by some class because events cannot be handled that occurs within Frame window. The next program shows how window can be closed and extended.

images

Figure 16.2 Output screen of Program 16.1

/*PROG 16.2 CLOSING WINDOW EVENT WITH FRAME */
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      MyFrame(String title)
      {
             super(title);
             Winadp wa = new Winadp(this);
             addWindowListener(wa);
      }
}
class Winadp extends WindowAdapter
{
      MyFrame mf;
      public Winadp(MyFrame f)
      {
             mf = f;
      }
      public void windowClosing(WindowEvent we)
      {
             mf.setVisible(false);
             System.exit(0);
      }
}
class JPS1
{
      public static void main(String args[])
      {
             Frame fr = new MyFrame("Frame Demo");
             fr.setVisible(true);
             fr.setSize(300, 300);
      }
}

Explanation: In this program, the class MyFrame extends the Frame class. The constructor of the MyFrame class takes title as String objects and passes it to the constructor of Frame class. Similar to adapter classes for applets has been seen in the previous chapter, one adapter class is created for handling the WINDOW_CLOSING event. The window listener is added using addWindowListener method. In this method, an object of Winadp class is passed as argument. It means the frame window will be receiving window events. The constructor of Winadp class takes reference of MyFrame class as argument. Recall this is necessary as to work with methods of MyFrame class and its parent class within Winadp class. In the overridden windowClosing method, the visibility of frame window is set to false using setVisible method and the program is terminated using System.exit(0). If not used, window will be hidden, but there will be no prompt/main window back. CTRL-C will have to be pressed .

images

Figure 16.3 Output screen of Program 16.2

In the main, the frame window is created using constructor of MyFrame class. The reference is stored in fr. Rest is simple to understand.

/*PROG 16.3 DISPLAY "HELLO" ON MOUSE CLICKED */
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      MyFrame(String title)
      {
             super(title);
             addWindowListener(new Winadp(this));
             addMouseListener(new MouseAdp(this));
      }
}
class Winadp extends WindowAdapter
{
      MyFrame mf;
      public Winadp(MyFrame f)
      {
             mf = f;
      }
      public void windowClosing(WindowEvent we)
      {
             mf.setVisible(false);
             System.exit(0);
      }
}
class MouseAdp extends MouseAdapter{
      MyFrame m;
      public MouseAdp(MyFrame ad)
      {
             m = ad;
      }
      public void mouseClicked(MouseEvent me)
      {
             Graphics g = m.getGraphics();
             g.drawString("Hello", me.getX(), me.getY());
      }
}
class JPS2{
      public static void main(String args[])
      {
         Frame fr = new MyFrame("Mouse Events in Frame Window");
         fr.setVisible(true);
         fr.setSize(300,250);
         fr.setBackground(Color.cyan);
         fr.setBackground(Color.blue);
      }
}

Explanation: The program is simple. Similar to handling window events using adapter class, the mouse event is handled here using adapter class. MouseAdp is created that extends MouseAdapter class in which the method mouseClicked is overridden. The method displays "Hello" wherever the mouse is clicked inside the frame window. In the main method, foreground color of the frame window is set using method setForeground and setBackground.

images

Figure 16.4 Output screen of Program 16.3

A number of other methods that have been used in the applet can be used here also. The most useful method is paint. If one wants to perform some drawings in the frame window, simply define paint method and write code in it. To see this simply add the paint method in the MyFrame class and run the program after compiling.

public void paint(Graphics g)
{
      g.drawRect(50,50,50,50);
      g.fillOval(100,100,50,50);
}
/*PROG 16.4 FRAME WITHIN APPLET */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      MyFrame(String title)
      {
             super(title);
             Winadp wa = new Winadp(this);
             addWindowListener(wa);
      }
}
class Winadp extends WindowAdapter
{
      MyFrame mf;
      public Winadp(MyFrame f)
      {
             mf = f;
      }
      public void windowClosing(WindowEvent we)
      {
             mf.setVisible(false);
             System.exit(0);
      }
}
public class Frame1 extends Applet
{
      public void init()
      {
             Frame fr = new MyFrame("Frame Demo");
             fr.setVisible(true);
             fr.setSize(300, 300);
      }
}

Explanation: The program is similar to the earlier program of creation of frame with window closing event but here instead of main method, applet class has been used. A new applet class Frame1 is created and inside it the coding for creation and display of frame window is written. Note in the program, the setBounds method is used for setting the x, y coordinate and width and height of the frame window.

images

Figure 16.5 Output screen of Program 16.4

/*PROG 16.5 EVENT HANDLING, BOTH IN APPLET AND FRAME */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class MyFrame extends Frame implements MouseListener
{
      MyFrame(String title)
      {
             super(title);
             Winadp wa = new Winadp(this);
             addWindowListener(wa);
             addMouseListener(this);
      }
      public void mouseClicked(MouseEvent me)
      {
             Graphics g = getGraphics();
             setForeground(Color.red);
             g.drawString("Frame Window",me.getX(),me.getY());
      }
      public void mouseExited(MouseEvent me){}
      public void mousePressed(MouseEvent me){}
      public void mouseReleased(MouseEvent me){}
      public void mouseEntered(MouseEvent me){}
}
class Winadp extends WindowAdapter
{
      MyFrame mf;
      public Winadp(MyFrame f)
      {
             mf = f;
      }
      public void windowClosing(WindowEvent we)
      {
             mf.setVisible(false);
             System.exit(0);
      }
}
public class Frame2 extends Applet implements MouseListener
{
      public void init()
      {
             Frame fr = new MyFrame("Frame Demo");
             fr.setVisible(true);
             fr.setBounds(150,150,250,250);
             addMouseListener(this);
      }
      public void mouseClicked(MouseEvent me)
      {
             Graphics g = getGraphics();
             setForeground(Color.blue);
             g.drawString("Applet Window",me.getX(),me.getY());
      }
      public void mouseExited(MouseEvent me){}
      public void mousePressed(MouseEvent me){}
      public void mouseReleased(MouseEvent me){}
      public void mouseEntered(MouseEvent me){}
}

images

Figure 16.6 Output screen of Program 16.5

Explanation: This program demonstrates how events can be handled both in frame window as well as in applet window. The code has been explained in the earlier programs, so no need to repeat it here again. One thing to note here is that both the classes MyFrame and Frame2 implement the interfaces and define the methods of the interfaces. Both the classes write the code in mouseClicked method and provide empty implementation of other methods of the interfaces.

16.4 AWT CONTROLS

This section discusses some of the GUI interface elements that are represented by subclasses of Component. It also introduces the event classes and listener interfaces associated with each type of component that have been seen earlier.

The Component class itself defines many useful methods that can be used with components of any type. Some of these have already been used in examples. Let comp be a variable that refers to any component. Then the following methods are available (among many others):

1.   comp.getSize() is a function that returns an object belonging to the class Dimension. This object contains two instance variables—comp.getSize().width and comp.getSize().height—that give the current size of the component. One warning: When a component is first created, its size is zero. The size will be set later, probably by a layout manager. A common mistake is to check the size of a component before that size has been set.

2.   comp.getParent() is a function that returns a value of type Container. The container is the one that contains the component, if any. For a top-level component such as a Window or Applet, the value will be null.

3.   comp.getLocation() is a function that returns the location of the top-left corner of the component. The location is specified in the coordinate system of the component's parent. The returned value is an object of type Point. An object of type Point contains two instance variables, x and y.

4.   comp.setEnabled(true) and comp.setEnabled(false) can be used to enable and disable the component. This is only useful for certain types of component, such as button. When a button is disabled, its appearance changes, and clicking on it will have no effect. There is a boolean-valued function, comp.getEnabled(), that can be called to discover whether the component is enabled.

5.   comp.setVisible(true) and comp.setVisible(false) can be called to hide or show the component.

6.   comp.setBackground(color) and comp.setForeground(color) set the background and foreground colors for the component. If no colors are set for a component, it inherits the colors of its parent container. The command comp.setFont(font) sets the default font that is used for text displayed on the component. (These should work for all components, but might not work properly for some of the standard components, depending on the version of Java.)

For the rest of this section, subclasses of Component will be discussed that represent common GUI components. Remember that using any component is a multi-step process. The component object must be created with a constructor and added to a container. In many cases, a listener must be registered to respond to events from the component, and in some cases, a reference to the component must be saved in an instance variable so that the component can be manipulated by the program after it has been created.

For adding components to the applet or any other type of window add method have to be used defined by the Component class. The method has six forms. Only the most commonly used forms and their signatures are shown below:

Component add(Component comp)

Here, comp is the component to be added to the applet or any other type of window. The method returns a reference to the component added.

For the removal of the component, the method remove can be used. It has three forms, but only the commonly used form is shown:

void remove(Component comp)

Here comp is the component to be removed.

The various controls supported by AWT are shown below by giving their class name. All these controls have Component as their super class, so all the methods of Component class can be used by these classes.

images

Apart from these classes, AWT provides classes for creating menus, dialogs, etc. They will be discussed in details later.

16.4.1 The Button Control

The Button class is used for creating the most frequently used component (i.e., a push button). The class defines two constructors:

1.   public Button()
This form of constructor constructs a button with an empty string for its label. Later, the label can be set using setLabel method.

2.   public Button(String label)
This form of constructor constructs a button with the specified label.

The commonly used methods of this class are as follows:

1.   public void addActionListener(ActionListener l)
This method adds the specified action listener to receive action events from this button. Action events occur when a user presses or releases the mouse over this button.

2.   public String getActionCommand()
This method returns the command name of the action event fired by this button. If the command name is null (default), this method returns the label of the button.

3.   public String getLabel()
This method returns the label of the button.

4.   public void setLabel(String label)
This method sets the button's label to be the specified string.

For handling events for the button, the listener for the button has to be added using addActionListener method. The parent class must implement the ActionListener interface. Whenever the button is clicked, the method actionPerformed is called and an object of ActionEvent is passed to it. In the actionPerformed method, the code for handling the button press event can be written.

A number of examples of Button control are provided.

/*PROG 16.6 DEMO OF BUTTON CLASS, WORKING WITH SINGLE BUTTON */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "button1" width = 200 height = 200>
</applet>
*/
public class button1 extends Applet implements ActionListener
{
      Button but; String disp = " ";
      public void init()
      {
             setBackground(Color.yellow);
             but = new Button("Click Me");
             add(but);
             but.addActionListener(this);
      }
      public void actionPerformed(ActionEvent AE)
      {
             disp = "You Clicked Me";
             repaint();
      }
      public void paint(Graphics g)
      {
             g.drawString(disp, 80, 100);
      }
}

Explanation: In this program, a button but is created using Button (Click Me); constructor form. This creates a button with a label Click Me. The button instance but is added to the applet window using add method. The applet class button implements the ActionListener interface so that the button press event can be handled. Using method addActionListener, a listener for the button is added. When the button is clicked, actionPerformed method is called. In the method the String object is initialized to You Clicked Me and repaint method calls the paint method. Thus msg is displayed at 30, 70 in the applet window. The empty constructor form and setLabel method could also be used as:

images

Figure 16.7 Output screen of Program 16.6

but = new Button();
but.setLabel("Click Me")
/*PROG 16.7 DEMO OF BUTTON CLASS, WORKING WITH TWO BUTTONS */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "button2" width = 200 height = 200>
</applet>
*/
public class button2 extends Applet implements ActionListener
{
     Button but1, but2; String disp = " ";
     public void init()
     {
            setBackground(Color.CYAN);
            but1 = new Button("Click Me");
            but2 = new Button("Click Me Too");
            add(but1);
            add(but2);
            but1.addActionListener(this);
            but2.addActionListener(this);
     }
     public void actionPerformed(ActionEvent AE)
     {
            String caption = AE.getActionCommand();
            if(caption.equals("Click Me"))
            disp = "Hello from button1";
            else if(caption.equals("Click Me Too"))
            disp = "Hello from button2";
            repaint();
     }
     public void paint(Graphics g)
     {
            g.drawString(disp, 10, 50);
     }
}

Explanation: This program is simple compared to the previous one but here there are two buttons. Code in the init method is simple to understand. Note listeners for both buttons have to be added. In the actionPerformed method, one can come to know which button was pressed. This is done by using the method getActionCommand, which returns the label of the button pressed. The label is compared with the label of both the buttons using equals method. Depending on which button was pressed, appropriate message is put into the msg. The same is displayed using paint method. In the output, msg is displayed when button2 is clicked.

images

Figure 16.8 Output screen of Program 16.7

/*PROG 16.8 DRAWING COLORFUL CRICLES ON BUTTON CLICK */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "button3" width = 250 height = 250>
</applet>
*/
public class button3 extends Applet implements ActionListener
{
      Button but1;
      int h, w;
      public void init()
      {
             setBackground(Color.black);
             but1 = new Button("Click Me");
             add(but1);
             but1.addActionListener(this);
             h = this.getSize().height;
             w = this.getSize().width;
      }
      public void actionPerformed(ActionEvent AE)
      {
       if (AE.getSource() == but1)
       {
             int x = (int)(Math.random() * 10000);
             int y = (int)(Math.random() * 10000);
             x = x % h;
             y = y % w;
             Graphics g = getGraphics();
             g.setColor(new Color(x%255,y%255,(x*y)%255));
             g.drawOval(x - 3, y - 3, 6, 6);
       }
      }
}

Explanation: In this program, circles of radius 6 are drawn in random colors anywhere on to the applet window. Note in the actionPerformed method getSource() method has been used. This method returns the Object that is responsible for the event. Coding in the method is simple to understand.

images

Figure 16.9 Output screen of Program 16.8

/*PRGO 16.9 COUNTING NUMBER OF TIMES BUTTON CLICKED */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "button4" width = 200 height = 100>
</applet>
*/
public class button4 extends Applet implements ActionListener
{
      Button but; String disp = " ";
      static int count = 0;
      public void init()
      {
             setBackground(Color.orange);
             but = new Button("Click Me");
             add(but);
             but.addActionListener(this);
      }
      public void actionPerformed(ActionEvent AE)
      {
             count++;
             disp = "You clicked me :=" + count + "times";
             repaint();
      }
      public void paint(Graphics g)
      {
             g.setColor(Color.BLACK);
             g.drawString(disp, 50, 50);
      }
}

Explanation: This program is simple. The number of times the button was clicked is to be counted. For this purpose, a static member count has been taken. The count is incremented by 1 each time the button is clicked in the actionPerformed method. This count is then concatenated with the String literal " You clicked me:= count times " and is displayed in paint method.

images

Figure 16.10 Output screen of Program 16.9

/*PROG 16.10 SHOWING AND HIDING BUTTONS */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "button5" width = 200 height = 100>
</applet>
*/
public class button5 extends Applet implements ActionListener
{
      Button but1, but2; String disp = " ";
      public void init()
      {
             setBackground(Color.CYAN);
             but1 = new Button("First");
             but2 = new Button("Second");
             add(but1);
             add(but2);
             but1.addActionListener(this);
             but2.addActionListener(this);
      }
      public void actionPerformed(ActionEvent AE)
      {
             String caption = AE.getActionCommand();
             if (caption.equals("First"))
             {
                      but1.setVisible(false);
                      but2.setVisible(true);
                      disp = "First Button := Hidden Second Button
                                                 := Visible";
             }
             else
             {
                      but1.setVisible(true);
                      but2.setVisible(false);
                      disp = "First Button := Visible Second
                      Button := Hidden";
             }
             repaint();
      }
      public void paint(Graphics g)
      {
             g.drawString(disp, 30, 70);
      }
}

images

Figure 16.11 Output screen of Program 16.10

Explanation: In the actionPerformed method, when the first button (with the caption " First") is clicked it is to be hidden and the second button (with the caption " Second ") displayed. When second button is clicked, the reverse is done (i.e., display the first and hide the second). This has been made possible by using the method setVisible seen earlier.

16.4.2 The Label Class

A Label object is a component for placing text in a container. A label displays a single line of read-only text (i.e., static text). The text can be changed by the application, but a user cannot edit it directly. The Label class defines the following constructors:

1.   public Label()
This form of constructor constructs an empty label. The text of the label is the empty string " ".

2.   public Label(String text)
This form of constructor constructs a new label with the specified string of text, left justified.

3.   public Label(String text, int alignment)
This form of constructor constructs a new label that presents the specified string of text with the specified alignment. Possible values for alignment are Label.LEFT, Label.RIGHT and Lable.CENTER.

The Label class defines a number of useful methods for getting text/alignment, setting text/alignment of the Label object. They are briefly discussed in the following.

1.   public int getAlignment()
This method returns the current alignment of this label. The returned values may be any of the Label.LEFT, Lable.RIGHT, and Label.CENTER.

2.   public void setAlignment(int alignment)
This method sets the alignment for this label to the specified alignment. Possible values may be Label.LEFT, Label.RIGHT and Label.CENTER.

3.   public String getText()
This method returns the text of this label as String object.

4.   public void setText(String text)
This method sets the text for this label to the specified text.

/*PROG 16.11 DEMO OF LABEL CLASS, WORKING WITH SINGLE LABEL */
import java.awt.*;
import java.applet.*;
/*
<applet code = "label1" width = 150 height = 150>
</applet>
*/
public class label1 extends Applet
{
      Label L1;
      public void init()
      {
             L1 = new Label("This is a Label");
             L1.setBackground(Color.cyan);
             L1.setForeground(Color.red);
             add(L1);
      }
}

images

Figure 16.12 Output screen of Program 16.11

Explanation: This program is simple to understand. Most important thing to note here is that label is placed onto the applet by the default layout manager, that is, FlowLayout manager from left to right. They will be discussed in the next section.

/*PROG 16.12 DEMO OF LABEL CLASS, WORKING WITH MULTIPLE LABELS */
import java.applet.*;
import java.awt.*;
/*
<applet code = "label2" width = 200 height = 75>
</applet>
*/
public class label2 extends Applet
{
      Label L[];
      public void init()
      {
             L = new Label[3];
             for (int i = 0; i < L.length; i++)
             {
                     L[i] = new Label("Label " + (i + 1));
                     L[i].setBackground(Color.cyan);
                     L[i].setForeground(Color.red);
                     add(L[i]);
             }
             L[0].setAlignment(Label.CENTER);
             L[1].setAlignment(Label.LEFT);
             L[2].setAlignment(Label.RIGHT);
      }
}

Explanation: In this program, an array of objects of Label class is created by the name L. The array is given length in the init method. Note each element of array L is initialized separately and assigned the text "Label 1", "Label 2", and "Label 3" in the for loop. Outside the for loop in the init method the alignment for various labels is set, but from the output it is clear that it has not worked. This is because the default layout manager which is FlowLayout has not been changed, so by default labels or any other component are placed to right.

images

Figure 16.13 Output screen of Program 16.12

16.4.3 The Checkbox Class

A check box is a graphical component that can be in either an "on"(true) or "off " (false) state. Clicking on a check box changes its state from "on" to "off " or from "off " to "on". Along with this status of on or off, there is a label associated with check box object. For check box there is the class Checkbox.

The class defines the following constructors:

1.   public Checkbox()
This form of constructor creates a check box with an empty string for its label. The state of this check box is set to "off ".

2.   public Checkbox(String label)
This form of constructor creates a check box with the specified label. The state of this check box is set to "off ".

3.   public Checkbox(String label, boolean state)
This form of constructor creates a check box with the specified label and sets the specified state.

4.   public Checkbox(String label, boolean state, CheckboxGroup group)

5.   public Checkbox(String label, CheckGroup group, boolean state)
The above two forms of constructors create a check box with the specified label, set to the specified state and in the specified check box group.

The most commonly used methods of these classes are discussed below:

1.   public String getLabel()
This method returns the label of this check box.

2.   public void setLabel(String label)
This method sets this check box's label to be the string argument.

3.   public boolean getState()
This method determines whether this check box is in the "on" or "off " state. The Boolean value true indicates the "on" state and false indicates the "off " state.

4.   public void setState(boolean state)
This method sets the state of this check box to the specified state. The Boolean value true indicates the "on" state, and false indicates the "off " state.

For handling the events for checkbox ItemListener interface have to be implemented in the parent window, that is, applet window or parent window. The listener is registered using the method addItemListener. Whenever the checkbox item state is changed, itemStageChanged method is called and an object of ItemEvent is passed to it. The method serves as an event handler for the checkbox state change event.

/*PROG 16.13 IMPLEMENTING CHECKBOX AND ITS EVENT METHODS VER 1 */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "checkbox" width = 150 height = 100>
</applet>
*/
public class checkbox1 extends Applet implements ItemListener
{
      String msg = " ";
      Checkbox ch1, ch2;
      public void init()
      {
             setBackground(Color.blue);
             ch1 = new Checkbox("Yes");
             ch2 = new Checkbox("No");
             add(ch1);
             add(ch2);
             ch1.addItemListener(this);
             ch2.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g){
             if (ch1.getState())
                      msg = "Yes is checked";
             else
                      msg = "Yes is not checked";
             g.drawString(msg, 10, 40);
             if (ch2.getState())
                      msg = "No is checked";
             else
                      msg = "No is not checked";
             g.drawString(msg, 10, 60);
      }
}

images

Figure 16.14 Output screen of Program 16.13

Explanation: This program creates two Checkbox instances with the name ch1 and ch2. The labels of these are "Yes" and "No". The applet class checkbox implements the ItemListener interface. Listener for both the checkboxes are added using addItemListener method. Whenever any of the checkbox's state is changed, the itemStateMethod method is invoked and an object of ItemEvent is passed to it. Inside the method, the repaint method causes paint to be invoked. In the paint method, the state of both the checkboxes is on else, returns false. Depending on the state of checkboxes, appropriate message is displayed using drawString method.

/*PROG 16.14 IMPLEMENTING CHECKBOX AND ITS EVENT METHODS VER 2*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "checkbox2" width = 200 height = 150>
</applet>
*/
public class checkbox2 extends Applet implements ItemListener
{
      String msg = " ";
      Checkbox ch1, ch2, ch3, ch4;
      public void init()
      {
             setBackground(Color.red);
             ch1 = new Checkbox("Sachin", null, true);
             ch2 = new Checkbox("Saurav");
             ch3 = new Checkbox("Yuvraj");
             ch4 = new Checkbox("Dhoni");
             add(ch1);
             add(ch2);
             add(ch3);
             add(ch4);
             ch1.addItemListener(this);
             ch2.addItemListener(this);
             ch3.addItemListener(this);
             ch4.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             if (ch1.getState())
                      msg = "Sachine is in 
";
             else
                      msg = "Sachine is out
";
             g.drawString(msg, 10, 60);
             if (ch2.getState())
                      msg = "Saurav is in
";
             else
                      msg = "Saurav is out
";
             g.drawString(msg, 10, 80);
             if (ch3.getState())
                      msg = "Yuvraj is in 
";
             else
                      msg = "Yuvraj is out
";
             g.drawString(msg, 10, 100);
             if (ch4.getState())
                      msg = "Dhoni is in
";
             else
                      msg = "Dhoni is out
";
             g.drawString(msg, 10, 120);
      }
}

images

Figure 16.15 Output screen of Program 16.14

Explanation: This program is similar to the previous one with the addition of two more Checkbox instances. Note also that the state of first Checkbox instance is set to true.

16.4.4 The CheckboxGroup Class

The CheckboxGroup class is used to group tighter a set of Checkbox buttons. Exactly one check box button in a CheckboxGroup can be in the "on" state at any given time. Pushing any button, sets its state to "on" and forces any other button in the "on" state into the "off" state. In appearance, they are round shaped, and not square, so sometimes they are also known as radio buttons.

In case of checkboxes any of the checkbox can be set or unset, but after combining a number of checkboxes under one group, only one checkbox can be set.

The class defines just one constructor:

public CheckboxGroup()

The constructor creates a new instance of CheckboxGroup. The two useful methods of this class are discussed below:

1.   public Checkbox getSelectedCheckbox()
This method gets the current choice from this check box group. The current choice is the check box in this group that is currently in the "on" state, or null if all check boxes in the group are off.

2.   public void setSelectedCheckbox(Checkbox box)
This method sets the currently selected check box in this group to be the specified check box. It sets the state of that check box to "on" and all other check boxes in the group to "off ".

/*PROG 16.15 IMPLEMENTING CHECKBOXGROUP AND ITS EVENT MEHTODS VER 1 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "checkbox3" width = 200 height = 100>
</applet>
*/
public class checkbox3 extends Applet implements ItemListener
{
      String msg = " ";
      Checkbox ch1, ch2, ch3;
      CheckboxGroup group;
      public void init()
      {
             setBackground(Color.pink);
             group = new CheckboxGroup();
             ch1 = new Checkbox("Yes", group, true);
             ch2 = new Checkbox("No", group, false);
             ch3 = new Checkbox("Cancel", group, false);
             add(ch1);
             add(ch2);
             add(ch3);
             ch1.addItemListener(this);
             ch2.addItemListener(this);
             ch3.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             msg = "You Selected ";
             Checkbox temp = group.getSelectedCheckbox();
             msg = msg + temp.getLabel();
             g.drawString(msg, 10, 50);
      }
}

images

Figure 16.16 Output screen of Program 16.15

Explanation: In this program, a CheckboxGroup instance by the name group is created. Three Checkbox instances ch1, ch2 and ch3 are created and all are made members of the group. Now, out of all three checkboxes, only one can be set any time. In the paint method, the currently selected checkbox instance is obtained using the method getSelectedCheckbox(). This is stored in the temporary reference temp of Checkbox class The label of this is obtained using getLabel method. This label is then appended to the string "You Selected" and displayed using drawString method.

/*PROG 16.16 IMPLEMENTING CHECKBOX AND ITS EVENT METHODS VER 2*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "checkbox4" width = 200 height = 100>
</applet>
*/
public class checkbox4 extends Applet implements ItemListener
{
      String msg = " ";
      Checkbox ch[];
      CheckboxGroup group;
      public void init(){
             setBackground(Color.LIGHT_GRAY);
             ch = new Checkbox[4];
             group = new CheckboxGroup();
             for (int i = 0; i < ch.length; i++)
             {
                      ch[i] = new Checkbox();
                      ch[i].setCheckboxGroup(group);
                      add(ch[i]);
                      ch[i].addItemListener(this);
             }
             ch[0].setLabel("Aishwarya Rai");
             ch[0].setState(true);
             ch[1].setLabel("Prity Zinta");
             ch[2].setLabel("Amrita Rao");
             ch[3].setLabel("Bipaha Basu");
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             msg = "You Like";
             msg += group.getSelectedCheckbox().getLabel();
             g.drawString(msg, 10, 80);
      }
}

images

Figure 16.17 Output screen of Program 16.16

Explanation: In this program, an array of checkboxes is created by the name ch of size 4. Using for loop all array elements are initialized with default constructor of Checkbox class. The array elements are assigned the Checkboxgroup instance group using the method setCheckboxGroup. The labels of each checkbox are set separately using setLabel method. The first check box is assumed to be selected. Coding in paint method is simple to understand.

16.4.5 The List Class

The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple ones. Any number of items can be shown at one time. The class provides the following constructors:

1.   public List()
This form of constructor creates a new scrolling list. By default, there are four visible lines, and multiple selections are not allowed.

2.   public List(int rows)
This form of constructor creates a new scrolling list initialized with the specified number of visible lines. By default, multiple selections are not allowed.

3.   public List(int rows, boolean msMode)
This form of constructor creates a new scrolling list initialized to display the specified number of rows. Note that if zero rows are specified, the list will be created with a default of four rows. Also note that the number of visible rows in the list cannot be changed after it has been created. If the value of msMode is true, the user can select multiple items from the list. If it is false, only one item at a time can be selected.

There are a number of useful methods of List class, which are discussed below:

1.   add
This method has two forms:

images public void add(String item)
This form of add method adds the specified item to the end of the scrolling list.

images public void add(String item, int index)
This form of add method adds the specified item to the scrolling list at the position indicated by the index. The index is zero based. If the value of the index is less than zero, or greater than or equal to the number of items in the list, the item is added to the end of the list.

2.   public String getItem(int index)
This method gets the item associated with the specified index.

3.   public String[]getItems()
This method gets the items in the list. It returns a string array containing items of the list.

4.   public int getItemCount()
This method returns the number of items in the list.

5.   public int getSelectedIndex()
This method returns the index of the selected item; if no item is selected, or if multiple items are selected, -1 is returned.

6.   public int[] getSelectedIndexes()
This method returns an array of the selected indexes on the scrolling list; if no item is selected, a zero-length array is returned.

7.   public String getSelectedItem()
This method returns the selected item on the list; if no item is selected, or if multiple items are selected, null is returned.

8.   public String[]getSelectedItems()
This method returns an array of the selected items on the scrolling list; if no item is selected, a zero-length array is returned.

9.   public void remove(String item)
This method removes the first occurrence of an item from the list.

10. public void remove(int position)
This method removes the item at the specified position from the scrolling list.

11. public void removeAll()
This method removes all items from the list.

12. public void select(int index)
This method selects the item at the specified index on the scrolling list.

If an application wants to perform some action based on an item in the list being selected or activated by the user, it should implement ItemListener or ActionListener as appropriate, and register the new listener to receive events from this list.

When an item is selected or deselected by the user, AWT sends an instance of ItemEvent to the list. When the user double-clicks on an item in a scrolling list, AWT sends an instance of ActionEvent to the list following the item event. AWT also generates an action event when the user presses the return key while an item in the list is selected.

/*PROG 16.17 CREATING LIST AND IMPLEMENTING ITS METHODS VER 1*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "list1" width = 200 height = 100">
</applet>
*/
public class list1 extends Applet implements ItemListener
{
      List PL;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.blue);
             PL = new List(4, true);
             PL.add("C++");
             PL.add("VC++");
             PL.add("Java");
             PL.add("C#");
             PL.select(2);
             add(PL);
             PL.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             int idx[];
             dispstr = "Seleted PL are";
             idx = PL.getSelectedIndexes();
             for(int i = 0;i<idx.length;i++)
             dispstr += PL.getItem(idx[i])+ " , ";
             g.drawString(dispstr, 10, 130);
      }
}

Explanation: In this program, a List instance PL of four items is constructed with multiple selections allowed. Names of four programming languages are added to the list PL. The third item is shown selected using select(2). The applet window implements ItemListener interface so whenever an item is selected or deselected using mouse click, an ItemEvent instance is sent to the itemStateChanged method. In this method, repaint method causes paint method to be called. In the paint method, an array of selected indexes is obtained using getSelectedIndexes method. Then using this array and getItem method, all selected list items are concatenated to the dispstr. The same is then displayed using drawString method.

images

Figure 16.18 Output screen of Program 16.17

/*PROG 16.18 CREATING LIST AND IMPLEMENTING ITS METHODS VER 2 */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "list2" width = 200 height = 100>
</applet>
*/
public class list2 extends Applet implements ActionListener
{
      List PL;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.cyan);
             PL = new List(4, true);
             PL.add("C++");
             PL.add("VC++");
             PL.add("Java");
             PL.add("C#");
             PL.select(2);
             add(PL);
             PL.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             String[] str = null;
             dispstr = "Selected PL are";
             str = PL.getSelectedItems();
             for (int i = 0; i < str.length; i++)
                      dispstr += str[i] + ",";
             g.drawString(dispstr, 10, 100);
      }
}

Explanation: This program is similar to the previous one but in this case ActionListener interface is implemented and listener is added using addActionListener method. Now, whenever an item in the list is double-clicked, an ActionEvent instance is passed to the method actionPerformed. In this method, all selected entries are returned using getSelectedItems method in the String array str. All array elements are then concatenated to the dispstr and then displayed. Note the same code which had been written in the previous program in the paint method, can be used here too; however, an alternative code has been used.

images

Figure 16.19 Output screen of Program 16.18

/*PROG 16.19 CREATING LIST AND IMPLEMENTING ITS METHODS VER 3 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "list3" width = 200 height = 200>
</applet>
*/
public class list3 extends Applet implements ActionListener
{
      List OS, PL;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.RED);
             OS = new List(4, true);
             PL = new List(4, true);
             OS.add("Window XP");
             OS.add("Linux");
             OS.add("Unix");
             OS.add("Window Vista");
             PL.add("C++");
             PL.add("VC++");
             PL.add("Java");
             PL.add("C#");
             PL.select(2);
             OS.select(1);
             add(OS);
             add(PL);
             OS.addActionListener(this);
             PL.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             int idx[];
             dispstr = "Selected OS are";
             idx = OS.getSelectedIndexes();
             for (int i = 0; i < idx.length; i++)
                      dispstr += OS.getItem(idx[i]) + ", ";
             g.drawString(dispstr, 10, 100);
             dispstr = "Selected PL are";
             idx = PL.getSelectedIndexes();
             for (int i = 0; i < idx.length; i++)
                      dispstr += PL.getItem(idx[i]) + ",";
             g.drawString(dispstr, 10, 120);
      }
}

images

Figure 16.20 Output screen of Program 16.19

Explanation: This program is simple to understand. The only difference it has from previous two programs is that in this case two lists have been worked with.

/*PROG 16.20 TRANSFERRING ITEMS BETWEEN LISTS */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "list4" width = 300 height = 100>
</applet>
*/
public class list4 extends Applet implements ActionListener
{
      List L1, L2;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.PINK);
             L1 = new List(4, false);
             L2 = new List(4, false);
             L1.add("Hari");
             L1.add("Man");
             L1.add("Vijay");
             L1.add("Mohan");
             L2.add("Anjana");
             L2.add("Hemangi");
             L2.add("Malvika");
             L2.add("Vipul");
             add(L1);
             add(L2);
             L1.addActionListener(this);
             L2.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             if (ae.getSource() == L1)
             {
                      L2.add(L1.getSelectedItem());
                      L1.remove(L1.getSelectedItem());
             }
             else if (ae.getSource() == L2)
             {
                      L1.add(L2.getSelectedItem());
                      L2.remove(L2.getSelectedItem());
             }
      }
}

images

Figure 16.21 Output screen of Program 16.20

Explanation: On double-clicking an item on any of the lists, the item is removed from that list and added to another. For example, when an item is in list L1 and when it is double-clicked, it must be added to list L2 and removed from list L1. In order to identify in which of the lists the item was clicked, the method getSource is used. Assume the list L1 in which an item is double-clicked. The item is added to the list L2 as:

L2.add(L1.getSelectedItem());

And removed from L1 as:

L1.remove(L1.getSelectedItem());

16.4.6 The Choice Class

The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of the menu. The menu lists a number of items; only the selected item is displayed. However, when the user clicks on the Choice component, the entire list is displayed, and the user can select one of the items from the list. There are three types of menu in Java: choice menu, pop-up menu, and pulldown menu. Pop-up and pull-down menus are not components. In fact, Choice components are not technically considered to be menus, but it is hard to find another word that adequately describes what they do.

The class defines just one default constructor.

public Choice()

Various useful methods of Choice class are discussed below:

1.   public void add(String item)
This method adds an item to this Choice menu.

2.   public String getItem(int index)
This method returns the string at the specified index in this Choice menu.

3.   public int getItemCount()
This method returns the number of items in this Choice menu.

4.   public int getSelectedItem()
This method returns the index of the currently selected item. If nothing is selected, it returns -1.

5.   public String getSelectedItem()
This method returns a representation of the current choice as a string.

6.   public void insert(StringItem, int index)
This method inserts the item into this choice at the specified position.

7.   remove

images public void remove(int position)
This method removes an item from the Choice menu at the specified position.

images public void remove(String item)
This method removes the first occurrence of item from the Choice menu.

8.   public void removeAll()
This method removes all items from the Choice menu.

9.   select
This method has two forms:

(i) public void select(int pos)
This method sets the selected item in this Choice menu to be the item at the specified position.

(ii) public void select(String str)
This method sets the selected item in this Choice menu to be the item whose name is equal to the specified string. If more than one item matches (is equal to) the specified string, the one with the smallest index is selected.

For handling events for Choice, the parent class has to implement ItemListener interface and listener has to be registered using addItemListener method. Whenever an item is selected from the Choice instance, event notification is sent to itemStateChanged method, as seen earlier with the List class.

/*PROG 16.21 DEMO OF CHOICE CLASS AND ITS METHOD VER 1*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "choice1" width = 200 height = 100>
</applet>
*/
public class choice1 extends Applet implements ItemListener
{
      Choice MC;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.red);
             MC = new Choice();
             MC.add("Sony Erricsion W200i");
             MC.add("Nokia N91");

             MC.insert("Motorola Motorazr",1);
             MC.add(" Sony Errcision W500i");

             MC.select(2);

             add(MC);
             MC.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             dispstr = "Selected Mobile is ";
             dispstr += MC.getSelectedItem();
             g.drawString(dispstr, 20, 50);
      }
}

images

Figure 16.22 Output screen of Program 16.21

Explanation: In this program, a Choice instance by the name MC is created. In this instance, few mobile set names are added and inserted. The default choice selected is String object at index 2 using select method. A listener is added for MC using addItemListener method. Whenever a new selection from Choice instance MC is made, itemStateChnaged method is called and an instance of ItemEvent is passed to it. In this method, repaint method calls paint method. In the paint method, the selected item is retrieved using getSelectedItem method and concatenated to dispstr. The same is displayed using drawString method.

/*PROG 16.22 DEMO OF CHOICE CLASS AND ITS METHOD VER 2 */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code ="choice2" width = 200 height = 200>
</applet>
*/
public class choice2 extends Applet implements ItemListener
{
      Choice PL, OS;
      String dispstr = " ";
      public void init()
      {
             setBackground(Color.PINK);
             OS = new Choice();
             PL = new Choice();

             OS.add("Window XP");
             OS.add("Linux");
             OS.add("Unix");
             OS.add("Window Vista");
             PL.add("C++");
             PL.add("VC++");
             PL.add("Java");
             PL.add("C#");

             PL.select("Java");

             add(OS);
             add(PL);

             OS.addItemListener(this);
             PL.addItemListener(this);
      }
      public void itemStateChanged(ItemEvent ie)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             dispstr = "Selected OS is ";
             dispstr += OS.getSelectedItem();
             g.drawString(dispstr, 20, 60);
             dispstr = "Selected PL is ";
             dispstr += PL.getSelectedItem();
             g.drawString(dispstr, 20, 80);
      }
}

images

Figure 16.23 Output screen of Program 16.22

Explanation: This program is simple compared to previous one with the difference that two Choice instances are being worked with, instead of one.

16.4.7 The Scrollbar Class

The scrollbar class embodies a scroll bar, a familiar user-interface object. A scroll bar provides a convenient means for allowing a user to select from a range of values. A scroll bar can be either horizontal or vertical. It has five parts as shown in Figure 16.24.

images

Figure 16.24 Scrollbar and its parts

The position of the tab specifies the currently selected value. The user can move the tab by dragging it or by clicking on any part of the scroll bar. On some platforms, the size of the tab tells what portion of a scrolling region is currently visible. It is actually the position of the bottom or left edge of the tab that represents the currently selected value.

A scroll bar has four associated integer values:

images min, which specifies the starting point of a range of values represented by the scroll bar, corresponding to the left or bottom edge of the bar.

images max, which specifies the end point of a range of values, corresponding to the right or top edge of the bar.

images visible, which specifies the size of the tab.

images value, which gives the currently selected value, somewhere in the range between min and max (visible).

The scrollbar class defines the following constructors:

1.   public Scrollbar()
This form of constructor creates a new vertical scroll bar. The default properties of the scroll bar are listed in Table 16.2.

Property Description Default value
orientation Indicates whether the scroll bar is vertical or horizontal. Scrollbar.VERTICAL
value Controls the location of the scroll bar's bubble. 0
visible amount The scroll bar's range, typically represented by the size of the scroll bar's bubble 10
minimum The minimum value of the scroll bar. 0
maximum The maximum value of the scroll bar 100
unit increment Amount the value changes when the Line Up or Line Down key is pressed, or when the end arrows of the scroll bar are clicked. 1
block increment Amount the value changes when the Page Up or Page Down key is pressed, or when the scrollbar track is clicked on either side of the bubble. 10

Table 16.2 Scrollbar properties

2.   public Scrollbar(int orientation)
This form of constructor creates a new scroll bar with the specified orientation. The orientation argument must take one of the two values, Scrollbar.HORIZONTAL or Scrollbar. VERTICAL, indicating a horizontal or vertical scroll bar, respectively.

3.   public Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
This form of constructor creates a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum value.

The various useful methods of Scrollbar class are discussed below:

1.   public int getBlockIncrement()
This method gets the block increment of this scroll bar. The block increment is the value that is added or subtracted when the user activates the block increment area of the scroll bar, generally through a mouse or keyboard that the scroll bar receives as an adjustment event.

2.   public void setBlockIncrement()
This method sets the block increment of this scroll bar.

3.   public int getMaximum()
This method returns the maximum value of this scroll bar.

4.   public void setMaximum(int newMaximum)
This method sets the maximum value of this scroll bar. When setMaximum is called, the maximum value is changed, and other values (including the minimum, the visible amount and the current scroll bar value) are changed to be consistent with the new maximum.

5.   public int getMinimum()
This method returns the minimum value of this scroll bar.

6.   public void setMinimum(int newMinimum)
This method sets the minimum value of this scroll bar.

7.   public int getOrientation()
The method returns the orientation of this scroll bar, either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.

8.   public void setOrientation(int Orientation)
This method sets the orientation for this scroll bar, either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.

9.   public int getUnitIncrement()
This method returns the unit increment for this scrollbar. The unit increment is the value that is added or subtracted when the user activates the unit increment area of the scroll bar, generally through a mouse or keyboard that the scroll bar receives as an adjustment event.

10. public void setUnitIncrement(int v)
This method sets the unit increment for this scroll bar.

11. public int getValue()
This method returns the current value of this scroll bar.

12. public void setValue(int newValue)
This method sets the value of this scroll bar to the specified value.

A scroll bar generates an event of type AdjustmentEvent whenever the user changes the value of the scroll bar. The associated AdjustmentListener interface defines one method, "adjustmentValueChanged(AdjustmentEvent evt)", which is called by the scroll bar to notify the listener that the value on the scroll bar has been changed. This method should repaint the display or make whatever other change is appropriate for the new value. The method evt.getValue() returns the current value on the scroll bar. If more than one scroll bar are used and it needs to be determined which scroll bar generated the event, evt.getSource() should be used to determine the source of the event.

The getAdjustmentType() of AdjustmentEvent class can be used to find out the type of event occurred on the scroll bar. Its signature is given below:

public int getAdjustmentType()

This method returns the type of adjustment that caused the value changed event. It will have one of the following values:

images UNIT_INCREMENT

images UNIT_DECREMENT

images BLOCK_INCREMENT

images BLOCK_DECREMENT

images TRACK

/*PROG 16.23 DEMO OF SCROLLBAR VER 1*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code = "scrollbar1" width = 200 height = 100>
</applet>
*/
public class scrollbar1 extends Applet implements
AdjustmentListener
{
      String msg = " ";
      Scrollbar SB;
      public void init()
      {
       setBackground(Color.cyan);
       SB=new Scrollbar(Scrollbar.HORIZONTAL,5,10,5,500);
       SB.setUnitIncrement(5);
       add(SB);
       SB.addAdjustmentListener(this);
      }
      public void adjustmentValueChanged(AdjustmentEvent ae)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             msg = "Value: " + SB.getValue();
             g.drawString(msg, 30, 50);
      }
}

images

Figure 16.25 Output screen of Program 16.23

Explanation: In this program, AdjustmentListener interface has been implemented in the applet window class scrollbar1. In the init method, a horizontal scroll bar is created with minimum value 5, maximum value 500 and visible amount of thumb size 10. The unit increment of 5 is set. For the Scrollbar instance SB, adjustment listener is added using the method addAdjustmentListener. Whenever either of the arrows or inside the scroll bar area is clicked or the mouse is dragged, the adjustmentValueChanged method is called. In this method, due to repaint method the paint method is called. In the paint method, current value of SB is shown using drawstring and getValue method.

/*PROG 16.24 DEMO OF SCROLLBAR VER2, CONTROLLING MOVEMENT OF TEXT */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "scrollbar2" width = 200 height = 300>
</applet>
*/
public class scrollbar2 extends Applet implements
AdjustmentListener
{
      String msg = " ";
      Scrollbar SB;
      int X = 10, Y = 70;
      public void init(){
         setBackground(Color.pink);
         SB = new Scrollbar(Scrollbar.VERTICAL,5,10,5, 500);
         SB.setUnitIncrement(5);
         add(SB);
         SB.addAdjustmentListener(this);
      }
      public void adjustmentValueChanged(AdjustmentEvent ae)
      {
         switch (ae.getAdjustmentType()){
             case AdjustmentEvent.UNIT_INCREMENT:
                    Y += 5;
                    break;
             case AdjustmentEvent.UNIT_DECREMENT:
                    Y -= 5;
                    break;
             case AdjustmentEvent.BLOCK_INCREMENT:
                    Y += 25;
                    break;
             case AdjustmentEvent.BLOCK_DECREMENT:
                    Y -= 25;
                    break;
         }
         repaint();
      }
      public void paint(Graphics g)
      {
             msg = "Moving Text you can see";
             g.setFont(new Font("Calisto MT", Font.BOLD, 20));
             g.setColor(Color.blue);
             g.drawString(msg, X, Y);
      }
}

images

Figure 16.26 Output screen of Program 16.24

Explanation: In the init() a vertical scroll bar is created by the name SB. The minimum and maximum values for this scroll bar are 5 and 500, respectively, and unit increment is 5. In the adjustment ValueChanged method, the type of events occurring onto the scroll bar are recognized. For UNIT_INCREMENT and UNIT_DECREMENT events the value of Y was incremented/decremented by 5. For the BLOCK_INCREMENT and BLOCK_DECREMENT event, the value of Y was incremented/decremented by 25. The X and Y coordinates are used for displaying the string "Moving Text you can see" using drawString method. Each time the down arrow is clicked, values of Y increments by 5 and string is displayed at new position. Thus, the string can be moved using events of scroll bar.

16.4.8 The Textfield Class

A TextField object is a text component that allows for the editing of a single line of text. The super class for this class is the TextComponent class. The users can enter/edit/cut/paste the text of the TextField object. It is also possible to set a TextField to be read-only so that the user can read the text that it contains but cannot edit it.

The class defines the following constructs:

1.   public TextField()
This form of constructor creates a new text field.

2.   public TextField(int columns)
This form of constructor creates a new empty text field with the specified number of columns. The columns specify the number of characters that should be visible in the text field. This is used to determine the width of the text field. (Because characters can be of different sizes, the number of characters visible in the text field might not be exactly equal to columns).

3.   public TextField(String text)
This form of constructor creates a text field initialized with the specified text.

4.   public TextField(String text, int columns)
This form of constructor creates a text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.

The various useful methods of TextField/TextComponent class are discussed below:

1.   public String getText()
This method returns the current text of the TextField object.

2.   public void setText(String t)
This method sets the text that is presented by this text component to be the specified text.

3.   public void select(int sStart, int sEnd)
This method selects the text between the specified start and end position.

4.   public String getSelectedText()
This method returns the selected text from the text that is presented by this text component.

5.   public void setEditable(boolean b)
This method sets the flag that determines whether or not this text component is editable. If the flag is set to true, this text component becomes user editable. If the flag is set to false, the user cannot change the text of this text component.

6.   public boolean isEditable()
This method indicates whether or not this text component is editable-true if this text component is editable; false otherwise.

7.   public void setEchoChar(char c)
This method sets the echo character for this text field. An echo character is useful for text fields where user input should not be echoed to the screen, as in the case of a text field for entering a password.

8.   public char getEchoChar()
This method returns the character that is to be used for echoing.

Every time the user types a key in the text field, one or more key events are sent to the text field. A KeyEvent may be one of three types: keyPressed, keyReleased or KeyTyped. The key event is passed to every keyListener or keyAdapter object which registered to receive such events using the component's addkeyListener method. (KeyAdapter object implements the keyListener interface.)

It is also possible to fire an ActionEvent. If action events are enabled for the text field, they may be fired by pressing the Return key.

/*PROG 16.25 DEMO OF TEXTFIELD VER 1, DISPLAYING ENTERED NAME ON BUTTON CLICK */
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 /*
 <applet code = "text1" width = 200 height = 100>
 </applet>
 */
 public class text1 extends Applet implements ActionListener
 {
       String msg = " ";
       TextField tf;
       Button b;
       Label L;
       public void init()
       {
              setBackground(Color.cyan);
              L = new Label("Enter your name here",
                                 Label.CENTER);
              add(L);
             tf = new TextField(20);
             add(tf);

             b = new Button("Click Me");
             add(b);

             b.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             Graphics g = getGraphics();
             msg = "Hello " + tf.getText();
             g.drawString(msg, 20, 75);
      }
}

Explanation: In this program, a Button instance b, a Label instance L and a TextField instance tf have been used. An action listener is added to the Button instance. When the program executes, and user presses the button after entering his/her name into the text box, and actionPerformed method is called. In this method, the entered text is retrieved using getText method and is appended to the msg string. The msg is then displayed.

images

Figure 16.27 Output screen of Program 16.24

/*PROG 16.25 DEMO OF TEXTFIELD VER 2, DISPLAYING ENTERED NAME AND PASSWORD WITH EVENT HANDLED BY TEXTFIELD BY TEXTFIELD ITSELF*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "text2" width = 200 height = 200>
</applet>
*/
public class text2 extends Applet implements ActionListener
{
      TextField TN, TP;
      public void init()
      {
             setBackground(Color.red);
             Label LN = new Label("Name: ");
             Label LP = new Label("Password: ");
             TN = new TextField(15);
             TP = new TextField(10);
             TP.setEchoChar('*'),

             add(LN);
             add(TN);
             add(LP);
             add(TP);

             TN.addActionListener(this);
             TP.addActionListener(this);
}
      public void actionPerformed(ActionEvent ae)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             g.drawString("Name: " + TN.getText(), 10, 70);
             g.drawString("Password: " + TP.getText(), 10, 90);
      }
}

Explanation: In this program, two labels and two text boxes are created for name and password. For the second TextField instance TP, the echo character "*" is set. Now whatever character is typed in this text box, '*' is displayed. After entering the text in any of the text boxes when the user presses the Enter key, ActionEvent is generated and actionPerformed method is called. In this method, the entered text is retrieved and displayed.

images

Figure 16.28 Output screen of Program 16.25

/*PROG 16.26 MAXIMUM OF TWO NUMBERS */
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 /*
 <applet code = "text3" width = 200 height = 200>
 </applet>
 */
 public class text3 extends Applet implements ActionListener
 {
       Button but1;
       String result = " ";
       boolean in = false;
       int num1, num2;
       TextField tf1, tf2;
       Label L1, L2;
       public void init()
       {
              setBackground(Color.green);
              L1 = new Label(" Enter first number: ");
              add(L1);
              tf1 = new TextField(10);
              add(tf1);
              L2 = new Label(" Enter second number: ");
              add(L2);
              tf2 = new TextField(10);
              add(tf2);
              but1 = new Button("Click For Maximum ");
              add(but1);
              but1.addActionListener(this);
       }
       public void actionPerformed(ActionEvent AE){
              try {
                      num1 = Integer.parseInt(tf1.getText());
                      num2 = Integer.parseInt(tf2.getText());
                      int ans = num1 > num2 ? num1 : num2;
                      result = result.valueOf(ans);
                      result = "Maximum is:= " + result;
              }
              catch (Exception E) {
                      result = "Error!!!";
              }
              repaint();
       }
       public void paint(Graphics g){
              g.setColor(Color.blue);
              g.drawString(result, 120, 120);
       }
}

images

Figure 16.29 Output screen of Program 16.26

Explanation: In the actionPerformed method, the two numbers entered into the two textboxes are first converted into integers. Maximum of two numbers are then stored in the variable ans. The int variable ans is then converted into the String using valueOf() method.

16.4.9 The TextArea Class

A TextArea object is a multi-line region that displays text. It can be set to allow editing or as read-only. A TextArea displays multiple lines and might include scroll bars that the user can use to scroll through the entire contents of the TextArea. Similar to TextField class, TextArea also has TextComponent class as its parent class.

The class defines following constructors:

1.   public TextArea()
This form of constructor creates a new text area with the empty string as text.

2.   public TextArea(String text)
This form of constructor creates a new text area with the specified text.

3.   public TextArea(int row, int columns)
This form of constructor creates a new text area with the specified number of rows and columns and the empty string as text.

4.   public TextString(String text, int rows, int columns)
This form of constructor creates a new text area with the specified text, and with the specified number of rows and columns.

5.   public TextArea(String text, int rows, int columns, int scrollbars)
This form of constructor creates a new text area with the specified text, and the rows, columns and scroll bar visibility as specified. All TextArea constructors refer to this one. The TextArea class defines several constants that can be supplied as values for the scrollbars argument:

images SCROLLBARS_BOTH

images SCROLLBARS_VERTICAL_ONLY

images SCROLLBARS_HORIZONTAL_ONLY

images SCROLLBARS_NONE

As TextComponent is also the parent class of TextArea so number of methods of TextComponent can be used with TextArea class. They are:

   getText(), setText(), getSelectedText(), select(), isEditable(), setEditable()

Some new methods of TextArea class are discussed below:

1.   public void append(String str)
This method appends the given text to the text area's current text.

2.   public void insert(String str, int pos)
This method inserts the specified text at the specified position in this text area.

3.   public void replaceRange(String str, int start, int end)
This method replaces text between the indicated start and end positions with the specified replacement text. The text at the end position will not be replaced. The text at the start position will be replaced (unless the start position is the same as the end position). The text position is zero based. The inserted substring may be of a different length than the text it replaces.

/*PROG 16.27 DEMO OF TEXTAREA CLASS */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code ="textarea1" width = 200 height =100>
</applet>
*/
public class textarea1 extends Applet implements
ActionListener
{
      TextArea text;
      Button b;
      public void init()
      {
             setBackground(Color.green);
             String mstr = "There are 3 ways to success
"+
                               "First is to go on 
"+
                               "Second is to go on 
"+
                               "And Third is to go on
"+
                               "
 Life is like an ice cream
"+
                               "eat it before it melts
";
             text = new TextArea(mstr, 5, 30);
             add(text);
             b = new Button("Select some text & click me");
             add(b);
             b.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             repaint();
      }
      public void paint(Graphics g)
      {
             String str = text.getSelectedText();
             g.drawString("Selected Text: "+str, 10, 145);
      }
}

images

Figure 16.30 Output screen of Program 16.27

Explanation: The TextArea instance does not generate any events other than focus events. In this program, a TextArea instance text is created and some text added to it. The rows and columns for this TextArea instance text are 5 and 30, respectively. After selecting some text from the contents of text area, the button is pressed, actionPerformed method is called. In the method, call to repaint method causes paint method to be called. In the paint, selected text is retrieved using getSelectedText method. The same is displayed using drawString method.

16.5 MENU AND MENUBARS

A menu is a list of choices. A menu bar displays a list of top-level menu choices. In Java, for implementing menu, a number of classes are provided like Menu, MenuBar and MenuItem.

A Menubar contains a number of instances of Menu each of which further contains a number of instances of MenuItem. Only Frames can have menu since they implement the MenuContainer interface. Therefore, an applet must create a frame in order to use menu.

A Menu class has MenuItem as its super class. A Menu object is a pull-down menu component that is deployed from a menu bar. Each item in a menu must belong to the MenuItem class. It can be an instance of MenuItem, a submenu (an instance of Menu), or a checkbox (an instance of Checkbox MenuItem). A CheckboxMenuItem instance will have a check mark next to it when it is selected.

The Menu class defines the following constructors:

1.   public Menu()
This form of constructor creates a new menu with an empty label.

2.   public Menu(String label)
This form of constructor creates a new menu with the specified label.
     In both the forms, the menu is not tear-off menu.

3.   public Menu(String label, boolean tearOff)
This form of constructor creates a new menu with the specified label, indicating whether the menu can be torn off.

After a Menu instance has been created, MenuItem instance can be added to it. All items in a menu must belong to the class MenuItem, or one of its subclasses. The default MenuItem object embodies a simple labelled menu item.

The MenuItem class defines the following constructors:

1.   public MenuItem()
This form of constructor creates a new MenuItem with an empty label and no keyboard shortcut.

2.   public MenuItem(String label)
This form of constructor creates a new MenuItem with the specified label and no keyboard shortcut.

3.   public MenuItem(String label, MenuShortcut s)
This form of constructor creates a menu item with an associated keyboard shortcut.

Once MenuItem instances have been created using one of the constructor forms, they can be added to the Menu instance using add method.

Checkable menu items can also be created. To do this, there is a subclass of the MenuItem named CheckboxMenuItem. This class represents a check box that can be included in a menu. Selecting the check box in the menu changes its state from "on" to "off " or from "off " to "on".

The CheckboxMenuItem class defines following constructors:

1.   public CheckboxMenuItem()
This method creates a check box menu item with an empty label. The item's state is initially set to "off ".

2.   public CheckboxMenuItem(String label)
This method creates a checkbox menu item with the specified label. The item's state is initially set to "off ".

3.   public CheckboxMenuItem(String label, boolean state) This method creates a check box menu item with the specified label and state.

To place the Menu instances on the MenuBar instance, it has to be created first. A MenuBar instance can be created with its default constructor form:

public MenuBar()

A menu bar is attached to the frame window using setMenuBar method.

/*PROG 16. 28 CREATING MENU AND MENUBAR WITH FRAME VER 1 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      String msg = " ";
      MyFrame(String title){
             super(title);
             //Menu bar created
             MenuBar mbar = new MenuBar();

             //Menu m is created by name File
             Menu m = new Menu ("File");
             //Three MenuItems are created
             m.add(new MenuItem("New"));
             m.add(new MenuItem("Open"));
             m.add(new MenuItem("Save"));

             //A separator is created (a visible line)
             m.addSeparator();

             //One more MenuItem
             m.add(new MenuItem("Quit"));

             //Menu is attached to menu bar
             mbar.add(m);

             //Menu bar is attached to frame window
             setMenuBar(mbar);
      }
}
public class menu{
             public static void main(String[]args){
                    Frame f = new MyFrame("Menu Demo Ver1");
                    f.setSize(200, 170);
                    f.setVisible(true);
             }
}

images

Figure 16.31 Output screen of Program 16.28

Various methods of Menu related classes are discussed below:

1.   public void setEnabled(boolean b)
This method sets whether or not this menu item can be chosen, that is, can be enabled or disabled.

2.   public boolean is Enabled()
This method checks whether this menu item is enabled.

3.   public String getLabel()
This method gets the label for this menu item to the specified label.

4.   public void setLabel(String label)
This method sets the label for this menu item to the specified label.

5.   public MenuItem add(MenuItem item)
This method adds the item to the specified Menu instance and returns the same.

6.   public boolean getState()
This method determines whether the state of this check box is "on" or "off ".

7.   public void setState(boolean b)
This method sets this check box menu item to the specified state. The Boolean value true indicates "on" while false indicates "off ".

Methods 6 and 7 belong to CheckboxMenuItem class.

Whenever a menu item from a menu is selected, an instance of ActionEvent is generated and passed to the method actionPerformed. For CheckboxMenuItem, an instance of ItemEvent is generated and passed to itemStateChanged method. For the events, the frame class must implement ActionListener and Item Listener interface. Note events are only generated for menu items and not for frame.

/*PROG 16. 29 CREATING MENU AND MENUBAR WITH FRAME VER 2 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      String msg = " ";
      MyFrame(String title)
      {
             super(title);
             //Menu bar created
             MenuBar mbar = new MenuBar();
             //Menu m is created by name File
             Menu m = new Menu("File");
             //Three MenuItems are created
             m.add(new MenuItem("New"));
             m.add(new MenuItem("Open"));
             m.add(new MenuItem("Save"));
             //A separator is created (a visible line)
             m.addSeparator();
             //One more MenuItem
             m.add(new MenuItem("Quit"));
             //Menu is attached to menu bar
             mbar.add(m);
             m = new Menu("Edit");
             m.add(new MenuItem("Cut"));
             m.add(new MenuItem("Copy"));
             m.add(new MenuItem("Paste"));
             m.addSeparator();
             m.add(new MenuItem("Select All"));
             mbar.add(m);
             m = new Menu("Help");
             m.add(new MenuItem("Index"));
             m.addSeparator();
             m.add(new MenuItem("About"));
             mbar.add(m);
             //Menu bar is attached to frame window
             setMenuBar(mbar);
             addWindowListener(new MWA());
      }
      class MWA extends WindowAdapter
      {
             public void windowClosing(WindowEvent we)
             {
                      setVisible(false);
                      System.exit(0);
             }
      }
}
public class menu2{
      public static void main(String[] args)
      {
             Frame f = new MyFrame("Menu Demo Ver1");
             f.setSize(200, 170);
             f.setVisible(true);
      }
}

images

Explanation: In this program, three different types of menus are created. For that just one Menu instance m is created. For the first menu labelled "File", three MenuItems are added, then a separator and one more MenuItem instance is added. Similarly, for other menus "Edit" and "Help" different MenuItem instances have been created. Note after creation of every menu with menu items they have been added to menu bar using add method. In the end, the MenuBar instance menu bar is attached to the menu using setMenuBar method.

For closing window event, window adapter class is created as an inner class. This has been explained in the previous chapter. In the main class menu, an instance of MyFrame class is created and "Menu Demo Ver1" passed as title of the Frame window. Note the code for the event handling for the selection of the menu items is not shown. This is shown in the next program.

/*PROG 16.30 CREATING MENU AND MENUBAR WITH FRAME VER 3 */
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
      MyFrame(String title)
      {
             super(title);
             MenuBar mbar = new MenuBar();
             Menu colors = new Menu("Demo");

             MenuItem item1 = new MenuItem("Red");
             MenuItem item2 = new MenuItem("Blue");
             MenuItem item3 = new MenuItem("Green");
             MenuItem item4 = new MenuItem("Black");
             colors.add(item1);
             colors.add(item2);
             colors.add(item3);
             colors.add(item4);
             mbar.add(colors);
             setMenuBar(mbar);
             item1.addActionListener(new MMH(this));
             item2.addActionListener(new MMH(this));
             item3.addActionListener(new MMH(this));
             item4.addActionListener(new MMH(this));
             addWindowListener(new MWA());
      }
      class MWA extends WindowAdapter
      {
             public void windowClosing(WindowEvent we)
             {
                      setVisible(false);
                      System.exit(0);
             }
      }
}
class MMH implements ActionListener
{
      MyFrame MF;
      public MMH(MyFrame mf){
             MF = mf;
      }
      public void actionPerformed(ActionEvent ae)
      {
             String arg = (String)ae.getActionCommand();
             if (arg.equals("Red"))
                    MF.setBackground(Color.red);
             else if (arg.equals("Green"))
                    MF.setBackground(Color.green);
             else if (arg.equals("Blue"))
                    MF.setBackground(Color.blue);
             else if (arg.equals("Black"))
                    MF.setBackground(Color.black);
             MF.repaint();
      }
}
public class menu3{
      public static void main(String[] args)
      {
             Frame f = new MyFrame("Menu Demo");
             f.setSize(250, 250);
             f.setVisible(true);
      }
}

images

Figure 16.32 Output screen of Program 16.30

Explanation: Whenever a menu item is selected ActionEvent is generated and an instance of it is passed to actionPerformed method. In the MyFrame constructor, three listeners are added for all four menus: item1, item2, item3 and item4. Note that a separate class MMH is created that implements ActionListener interface. In the constructor of MyFrame when listener is added for the menus using addActionListener, as an argument, an instance of MMH class is passed. The constructor of MMH class takes a reference of the MyFrame class. In the actionPerformed method, the label of the currently selected menu item is retrieved using getActionCommand and stored in the arg, which is compared with any of the label "Red", "Green", "Blue" and "Black". Depending on which menu item was selected, the background color of the frame window is set to that color.

16.5.1 Adding Shortcut Key to Menu

Shortcut keys to menu items can be added using the MenuShortcut class. The MenuShortcut class represents a keyboard accelerator for a MenuItem. Menu shortcuts are created using virtual keycodes, not characters. The class provides two constructors for creating shortcuts:

1.   public MenuShortcut(int key)

2.   public MenuShortcut(int key, boolean Spress)

The first form of constructor creates a new MenuShortcut for the specified virtual keycode. The key is the virtual keycode that would be returned using KeyEvent class if this key were pressed.

In the second form, if Spress is true, the shift key has to be pressed along with the Strl modifier.

Both the forms can be used as:

 MenuShortcut ms = new MenuShortcut(KeyEvent.VK_R);

If item is the MenuItem created earlier, the above created shortcut can be set using setShortcut method as:

 item.setShortcut(ms);

Now, the MenuItem item can be selected using Ctrl+R key. In case the shortcut is created as:

MenuShortcut ms = new MenuShortcut(KeyEvent.VK_R, true);

Then Ctrl+Shift+R key has to be pressed to select the item.

/*PROG 16.31 DEMO OF ADDING SHORTCUT KEYS TO MENUS */
    import java.awt.*;
    import java.awt.event.*;
    class MyFrame extends Frame
    {
         MyFrame(String title)
         {
               super(title);
               MenuBar mbar = new MenuBar();
               Menu shapes = new Menu("Demo");
               MenuItem item1 = new MenuItem("Circle");
               MenuItem item2 = new MenuItem("Rectangle");
               MenuItem item3 = new MenuItem("Ellipse");
               shapes.add(item1);
               shapes.add(item2);
               shapes.add(item3);
               mbar.add(shapes);
               MenuShortcut ms1 = new MenuShortcut(KeyEvent.VK_C);
               MenuShortcut ms2 = new MenuShortcut(KeyEvent.VK_R,
                                                         true);
               MenuShortcut ms3 = new MenuShortcut(KeyEvent.VK_E);

               item1.setShortcut(ms1);
               item2.setShortcut(ms2);
               item3.setShortcut(ms3);
               setMenuBar(mbar);

               item1.addActionListener(new MMH(this));
               item2.addActionListener(new MMH(this));
               item3.addActionListener(new MMH(this));

               addWindowListener(new MWA());
      }
      class MWA extends WindowAdapter {
             public void windowClosing(WindowEvent we)
             {
                      setVisible(false);
                      System.exit(0);
             }
      }
}
class MMH implements ActionListener{
      MyFrame MF;
      public MMH(MyFrame mf){
             MF = mf;
      }
      public void actionPerformed(ActionEvent ae){
             String arg = (String)ae.getActionCommand();
             Graphics g = MF.getGraphics();
             g.setColor(Color.blue);
             if (arg.equals("Circle"))
                   g.drawOval(150, 100, 50, 50);
             else if (arg.equals("Rectangle"))
                   g.drawRect(30, 60, 40, 60);
             else if (arg.equals("Ellipse"))
                   g.drawOval(90, 80, 40, 30);
      }
}
public class menu4{
      public static void main(String args[]){
             Frame f = new MyFrame("Setshortcut demo");
             f.setSize(250, 250);
             f.setVisible(true);
      }
}

images

Figure 16.33 Output screen of Program 16.31

Explanation: The program is similar to the previous one but here shortcuts for menu items have been added. The menu items are for drawing various shapes. Creation of menu shortcut and adding them to menu items is discussed in theory part.

16.6 POPUP MENUS

A Popup menu is a menu which can be dynamically popped up at a specified position within a component. It is implemented in java by class PopupMenu. Popup menus differ from all the components discussed above because they are not components and they are not usually visible. The user calls up a popup menu by performing some platform-dependent action with the mouse. For example, this might mean clicking with the right mouse button, or clicking the mouse while holding down the control key.

A pop-up menu is an object belonging to the class PopupMenu. A newly created pop-up menu is empty. Items can be added to the menu with its add(String) method. A separator line can be added with the addSeparator() method (There's a lot more one can do with menu items). If pmenu is a popup menu, it can be added to a component, comp, by calling comp.add(pmenu). However, this does not make the menu appear on the screen. To make a menu appear, a program has to call pmenu.show(comp, x, y). The pop-up menu appears with its upper-left corner at the point (x, y), where the coordinates are given in comp's coordinate system.

The class defines following constructors:

1.   public PopupMenu()
This form of constructor creates a new popup menu with an empty name.

2.   public PopupMenu(String label)
This form of constructor creates a new popup menu with the specified name.

It is not much more difficult to use popup menus in a program than it is to use the above components. A popup menu generates an ActionEvent when the user selects a command from the menu. The action command associated with that event is the label of the menu item that was selected. One can register an ActionListener with the menu to listen for commands from the menu.

Mouse events have to be listened from the component. A mouseEvent, evt, has a boolean valued method, evt.isPopupTrigger() that one can call to determine whether the user is trying to pop up a menu. This could theoretically occur in either the mosuePressed or in the mouseReleased method, so one should test for the pop-up trigger in both of these methods. The mousePressed method might look something like this (mouseReleased would be similar):

public void mousePressed(MouseEvent evt)
{
      if(evt.isPopupTrigger())
       {
        int x = evt.getX();
        int y = evt.getY();
        pmenu.show(this, x, y);
       }
}

Note that this method just make the menu appear on the screen. Any command generated by that menu must be handled elsewhere, in an actionPerformed method.

/*PROG 16.32 DEMO OF POPUP MENU */
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements MouseListener
{
      PopupMenu colors;
      MyFrame(String title)
      {
             super(title);
             colors = new PopupMenu();
             MenuItem item1 = new MenuItem("Red");
             MenuItem item2 = new MenuItem("Blue");
             MenuItem item3 = new MenuItem("Green");

             colors.add(item1);
             colors.add(item2);
             colors.add(item3);

             add(colors);

             colors.addActionListener(new MMH(this));
             addWindowListener(new MWA());
             addMouseListener(this);
      }
      public void mousePressed(MouseEvent evt)
      {
             if (evt.isPopupTrigger())
             {
                      int x = evt.getX();
                      int y = evt.getY();
                      colors.show(this, x, y);
             }
      }
      public void mouseReleased(MouseEvent evt)
      {
             if (evt.isPopupTrigger())
             {
                      int x = evt.getX();
                      int y = evt.getY();
                      colors.show(this, x, y);
             }
      }
      public void mouseExited(MouseEvent me) { }
      public void mouseClicked(MouseEvent me) { }
      public void mouseEntered(MouseEvent me) { }

      class MWA extends WindowAdapter
      {
             public void windowClosing(WindowEvent we)
             {
                      setVisible(false);
                      System.exit(0);
             }
      }
}
class MMH implements ActionListener
{
      MyFrame MF;
      public MMH(MyFrame mf)
      {
             MF = mf;
      }
      public void actionPerformed(ActionEvent ae)
      {
             String arg = (String)ae.getActionCommand();
             if (arg.equals("Red"))
                    MF.setBackground(Color.red);
             else if (arg.equals("Green"))
                    MF.setBackground(Color.green);
             else if (arg.equals("Blue"))
                    MF.setBackground(Color.blue);
             MF.repaint();
      }
}
public class menu5
{
      public static void main(String[] args)
      {
             Frame f = new MyFrame("Demo Popup menu");
             f.setSize(200, 200);
             f.setVisible(true);
      }
}

images

Figure 16.34 Output screen of Program 16.32

Explanation: The code in the constructor of MyFrame is easy to understand. An empty PopupMenu instance colors is created. Number of menu items are added to this PopupMenu instance colors. After adding menu items to colors, it is added to the frame window. Note actionListener is added only to the PopupMenu instance colors and not to all menu items. A mouse listener is also added to the frame window. Whenever the mouse pressed or mouse released event occurs, an instance of MouseEvent is passed to the mouseReleased and mousePressed method. Inside these methods, using isPopupTrigger method, it is checked whether or not this mouse event is the popup menu trigger event for the platform. If it is, then popup menus is shown at the current mouse position. When the popup menu appears during execution, any of the menu items can be selected. This works same as seen earlier, difference is only that menu is not attached to the menu bar.

16.7 DIALOGS

Like a frame, a dialog box is a separate window. Unlike a frame, however, a dialog box is not completely independent. Every dialog box is associated with a frame, which is called its parent. The dialog box is dependent on its parent. For example, if the parent is closed, the dialog box will also be closed.

Dialog boxes can be either modal or modeless. When a modal dialog is created, its parent frame is blocked. That is, the user will not be able to interact with the parent or even bring the parent to the front of the screen until the dialog box is closed. Modeless dialog boxes do not block their parents in the same way, so they seem a lot more like independent windows.

In Java, a dialog box is an object belonging to the class Dialog or to one of its subclasses. A Dialog cannot have a menu bar, but it can contain other GUI components, and it generates the same WindowEvents as a Frame. Dialog objects can be either modal or modeless. A parameter to the constructor specifies which it should be. Most commonly used constructor of the Dialog class is shown below:

1.   public Dialog(Frame owner)
This form of constructor creates an initially invisible, non-modal Dialog with an empty title and the specified owner frame.

2.   public Dialog(Frame owner, boolean modal)
This form of constructor creates an initially visible Dialog with an empty title, the specified owner frame and modality. If modal is true the dialog box is Modal and if false then it is false.

3.   public Dialog(Frame owner, String title, boolean modal)
This form of constructor creates an initially invisible Dialog with the specified owner frame, title, and modality.

When a dialog box is closed, dispose() method must be called. The method is defined by parent of the Dialog class i.e. Window class. Its signature is shown below:

 public void dispose()

The method releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Component will be destroyed, any memory they consumes will be returned to the OS, and they will be marked as undisplayable.

/*PROG 16.33 DEMO OF DIALOG VER 1*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class dialog extends Dialog implements ActionListener
{
      dialog(Frame parent, String title)
      {
             super(parent, title, false);
             setLayout(new FlowLayout());
             setSize(300, 200);
             Button but1 = new Button("Close");
             add(but1);
             but1.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             dispose();
             System.exit(0);
      }
}
class MyFrame extends Frame
{
      public static void main(String[] args)
      {
       dialog d = new dialog(new MyFrame(), "Demo Dialog");
       d.setVisible(true);
      }
}

Explanation: In the program class dialog extends Dialog class and implements the ActionListener interface. The interface is needed as a button is created on to the dialog window. The constructor of the dialog class takes two parameter of Frame and String type respectively. Using super the constructor of parent class Dialog is called and three parameters are passed. The two are from constructor of dialog class and third parameter being false represents a modeless dialog box. The default layout for a Dialog class is BorderLayout, so it is changed to FlowLayout using setLayout method. A button to the dialog window and also a listener using addActionListener method are added. In the actionPerformed dispose method is called for closing the dialog and to terminate the program System.exit(0) is called.

images

Figure 16.35 Output screen of Program 16.33

The class MyFrame extends the Frame class. In the main method, an object d of dialog class is created using the constructor. In the constructor, an instance of MyFrame class is passed and String "Demo Dialog" that denotes title of the dialog window. The dialog window must be shown by a call to setVisible method and passing argument true.

/*PROG 16.34 DEMO OF DIALOG VER 2 */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "dialog1" width = 200 height = 200>
</applet>
*/
class dialog extends Dialog implements ActionListener
{
      dialog(Frame parent, String title)
      {
             super(parent, title, false);
             setLayout(new FlowLayout());
             setSize(300, 200);
             Button but1 = new Button("Close");
             add(but1);
             but1.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
             dispose();
             System.exit(0);
      }
}
class MyFrame extends Frame
{
      MyFrame(String title)
      {
             super(title);
             setSize(200, 200);
      }
}
public class dialog1 extends Applet{
      public void init()
      {
             setBackground(Color.pink);
             dialog d = new dialog(new MyFrame("Hello"), "First");
             d.setVisible(true);
      }
}

images

Figure 16.36 Output screen of Program 16.34

Explanation: The program is similar to previous one with the difference that instead of main method, applet window is used. In the program, there is one additional class dialog1 that denotes our applet window. The coding which was in the main in the previous program is now in init method of dialog1 class.

/*PROG 16.35 DEMO OF DIALOG VER 3 */
import java.awt.*;
import java.awt.event.*;
class dialog extends Dialog implements ActionListener
{
      dialog(Frame parent, String title)
      {
         super(parent, title, false);
         setLayout(new FlowLayout());
         setSize(150, 100);
         add(new Label("Press OK to exit", Label.CENTER));
         Button but1 = new Button("OK");
         add(but1);
         but1.addActionListener(this);
         Button but2 = new Button("Cancel");
         add(but2);
            but2.addActionListener(this);
      }
      public void actionPerformed(ActionEvent ae)
      {
            String arg = (String)ae.getActionCommand();
            if (arg.equals("OK"))
            dispose();
      }
}
class MyFrame extends Frame implements ActionListener
{
      MyFrame(String title)
      {
             super(title);
             MenuBar mbar = new MenuBar();
             Menu m = new Menu("Demo");
             MenuItem item1 = new MenuItem("Show Dialog");
             m.add(item1);
             mbar.add(m);
             setMenuBar(mbar);
             item1.addActionListener(this);
             addWindowListener(new MWA());
      }
      class MWA extends WindowAdapter
      {
             public void windowClosing(WindowEvent we)
             {
                      setVisible(false);
                      System.exit(0);
             }
      }
      public void actionPerformed(ActionEvent ae)
      {
       String arg = (String)ae.getActionCommand();
       if (arg.equals("Show Dialog"))
       {
         dialog d=new dialog(new MyFrame("Hello"),"First");
         d.setVisible(true);
       }
      }
}
public class dialog2
{
      public static void main(String[] args)
      {
             Frame f = new MyFrame("Menu Demo");
             f.setSize(250, 250);
             f.setVisible(true);
      }
}

Explanation: In this program, the dialog box is called and displayed on clicking a menu item. The class dialog represents a dialog window. It is similar to classes seen earlier. In the constructor of this dialog class, one label and two buttons are added. When "OK" button is pressed the dialog box will be disposed.

images

Figure 16.37 Output screen of Program 16.35

In the MyFrame class constructor a menu is created. In the menu, just one menu item is added by the name "Show Dialog". When this menu item is clicked, actionPerformed method will be called. In the method an instance of dialog class is created and displayed using setVisible method by passing argument true.

In the dialog box when OK button is pressed, actionPerformed method is called in the dialog class and code in the method disposes the dialog box.

16.8 THE FILEDIALOG CLASS

The FileDialog class displays a dialog window from which the user can select file. It is a subclass of Dialog class. The dialog window provided by an object of the FileDialog class is the standard file selection window which the operating system provides. It is modal dialog box. Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file.

The class defines the following frequently used constructors:

1.   public FileDialog(Frame parent)
This form of constructor creates a file dialog for loading a file. The title of the file dialog is initially empty.

2.   public FileDialog(Frame parent, String title)
This form of constructor creates a file dialog window with the specified title of loading a file. The file shown are those in the current directory.

3.   public FileDialog(Frame parent, String title, int mode)
This form of constructor creates a file dialog window with the specified title for loading or saving file. If the value of mode is LOAD, then the file dialog is finding a file to read, and the files shown are those in the current directory. If the value of mode is SAVE, the file dialog is finding a place to write a file.

LOAD and SAVE are two properties of the FileDialog class.

/*PROG 16.36 DEMO OF FILEDIALOG VER 1 */
import java.awt.*;
import java.awt.event.*;
class FDDemo
{
      public static void main(String args[])
      {
       FileDialog fd;
       fd = new FileDialog(new Frame("Demo"),"File Dialog");
             fd.setVisible(true);
      }
}

images

Figure 16.38 Output screen of Program 16.36

Explanation: The program is self-explanatory.

/*PROG 15.37 DEMO OF FILEDIALOG VER 2 */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "FDDemo1" width = 200 height = 200>
</applet>
*/
class MyFrame extends Frame{
      MyFrame(String s)
      {
             super(s);
             setSize(200, 200);
      }
}
public class FDDemo1 extends Applet{
      FileDialog fd;
      Frame f;
      public void init(){
             setBackground(Color.orange);
             f = new MyFrame("Demo");
             fd = new FileDialog(f, "File Dialog");
             fd.setVisible(true);
      }
      public void paint(Graphics g) {
             g.drawString("File selected is " + fd.getFile(),
                               20, 50);
             String d = "Directory of the File is " +
                            fd.getDirectory();
             g.drawString(d, 20, 70);
      }
}

images

Figure 16.39 Output screen of Program 16.37

Explanation: This time an applet is created instead of an application for the creation of file dialog. The program also demonstrates how selected file name and directory name can be retrieved using getFile and getDirectory method.

/*PROG 16.38 DEMO OF FILEDIALOG VER 3 */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/*
<applet code = "FDDemo2" width = 200 height = 200>
</applet>
*/
class MyFrame extends Frame
{
      MyFrame(String s)
      {
             super(s);
             setSize(200, 200);
      }
}
public class FDDemo2 extends Applet{
      FileDialog fd;
      Frame f;
      byte b[];
      String s = null;
      public void init()
      {
       setBackground(Color.yellow);
       f = new MyFrame("Demo");
       fd = new FileDialog(f,"File Dialog");
       fd.setVisible(true);
       String f = fd.getFile();
       try {
             FileInputStream fis = new FileInputStream(f);
             b = new byte[64*64];
             fis.read(b);
             s = new String(b);
             fis.close();
       }
       catch(Exception E) {
             s = "Error in opening file";
       }
       TextArea ta = new TextArea(s, 15, 30);
             add(ta);
      }
}

images

Figure 16.40 Output screen of Program 16.38

Explanation: In this program, the selected file from file dialog is retrieved and opened using FileInputStream. The contents of file are read using read method and stored in byte array b. the size of array is chosen 64*64 as an approximation of size of file. The byte array is converted into String s. the string is added as contents of the TextArea instance tb of 15 rows and 30 columns.

16.9 PONDERABLE POINTS

1.   AWT stands for Abstract Window Toolkit. The toolkit is defined within the java.awt package. It contains all of the classes for creating user interfaces like Buttons, Labels, TextBox, Lists etc, and for painting graphics and images.

2.   Component class is the topmost class in the window hierarchy.

3.   A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.

4.   A generic AWT container object is a component that can contains other AWT components. The Container class is the subclass of the Component class. Containers (Frames, Dialogs, Windows and Panels) can contains component and are themselves components, thus can be added to Containers.

5.   A panel provides space in which an application can attach any other component, including other panels. A Panel is a container that does not exist independently. It is a plain rectangular area.

6.   In Java, a program can open an independent window by creating an object of type Frame. A Frame has a tile, displayed in the title bar at the top of the window. It can have a menu bar containing one or more pull-down menus.

7.   A Frame can be used within an applet or in an application program.

8.   The component class is the base class for the AWT component.

9.   For handling various AWT components, the respective listener interfaces are given below:

    Button                ActionListener
    Checkbox              ItemListener
    CheckboxGroup         ItemListener
    List                  ItemListener, ActionListener
    Choice                ItemListener
    ScrollBar             Adjustment Listener
    Menu                  ActionListener

10. A Label object is a component for placing text in a container. A label displays a single line of readonly text i.e. static text.

11. A check box is a graphical component that can be in either an "on" (true) or "off " (false) state. Clicking on a check box changes its state from "on" to "off ", or from "off " to "on".

12. The CheckboxGroup class is used to group together a set of Checkbox buttons. Exactly one check box button in a CheckboxGroup can be in the "on" state at any given time.

13. The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items.

14. The Choice class presents a pop-up menu of choice. The current choice is displayed as the title of the menu. The menu lists a number of items. Only the selected item is displayed.

15. The Scrollbar class embodies a scroll bar, a familiar user-interface object. A scroll bar provides a convenient means for allowing a user to select from a range of values. A scroll bar can be either horizontal or vertical.

16. A TextField object is a text component that allows for the editing of a single line of text.

17. A TextArea object is a multi-line region that displays text. It can be set to allow editing or to be read-only. A TextArea displays multiple lines and might include scroll bars that the user can use to scroll through the entire contents of the TextArea.

18. A menu is a list of choices. A menu bar displays a list of top-level menu choice.

19. Only Frame can have menus since they implement the MenuContainer interface. Therefore an applet must create a frame in order to use menus.

20. Each menu item is an instance of MenuItem class attached to the menu.

21. Shortcut keys to menu items can be added using the MenuShortcut class. The MenuShortcut class represents a keyboard accelerator for a MenuItem. Menu shortcuts are created using virtual keycodes.

22. A Popup menu is a menu which can be dynamically popped up at a specified position within a component. It is implemented in java by class PopupMenu.

23. Like a frame, a dialog box is a separate window. Unlike a frame, however, a dialog box is not completely independent. Every dialog box is associated with a frame, which is called its parent.

24. Dialog boxes can be either modal or modeless. When a modal dialog is created its parent frame is blocked. That is, the user will not be able to interact with the parent or even bring the parent to the front of the screen until the dialog box is closed. Modeless dialog boxes do not block their parents in the same way, so they seem a lot more like independent windows.

25. In Java, a dialog box is an object belonging to the class Dialog or to one of its subclasses.

26. The FileDialog class displays a dialog window from which the user can select a file. It is a subclass of Dialog class.

REVIEW QUESTIONS

1.   What do you mean by Abstract Window Toolkit?

2.   What are the different types of layout managers in Java?

3.   What are the different components of Abstract Window Toolkit?

4.   Explain the procedure to design menu in Java?

5.   Differentiate between text area and text box.

6.   Differentiate between the Component and Container class.

7.   Explain inset value and how you can set the inset values.

8.   What is the difference between checkbox and checkbox group?

9.   Write a Java program using checkboxes to display different presidents' names.

10. Write a Java program to display the different TV channels using checkboxgroup.

11. Write a Java program to display the different DLF-IPL 20/20 team names using checkboxes and checkboxgroup.

12. Write a Java program to display the different prices of the books using the choice object.

13. Write Java program to display the different car names using list object.

14. Write a Java program to display the different IIT's names in India using the choice object and list object.

15. Create a menu is a frame as shown below:

images

The Books menu has the following items: C, C++, Java, Oracle, VB, and ASP. The language menu consists of French, German, English, Tamil, and Hindi. The File menu has the following: Titanic, Jurassic Park, Tomorrow never Dies, Jeans, and Slumdog. The search engine consists of Yahoo, Hotmail, Sify, Google, and Lycos.

Multiple Choice Questions

1.   _______________ is the topmost class in the window hierarchy

(a) Component

(c) Container

(b) Event

(d) Window

2.   Match the following:

1. Button           a. ItemListener

2. Checkbox     b. ActionListener

3. ScrollBara.    c. AdjustmentListener

(a) 1-a, 2-b, 3-c

(b) 1-b, 2-c, 3-a

(c) 1-c, 2-a, 3-b

(d) 1-b, 2-a, 3-c

3.   A _______________ object is a component for placing text in a container.

(a) Textbox

(c) Label

(b) Checkbox

(d) None of the above

4.   The _______________ class is used to group together a set of Checkbox buttons.

(a) TextArea

(b) CheckboxGroup

(c) CheckBoxGroup

(d) MenuShortcut

5.   Which is the constructor of Frame class

(a) void Frame()

(b) public setFrame()

(c) public Frame(String title)

(d) void Frame(String title)

6.   Which of the following methods is used to returns the text of the label as String object

(a) public String getText()

(b) public void getText()

(c) public Char getText(String text, String s)

(d) None of the above

7.   Which is the method of Checkbox class

(a) public String getLabel()

(b) public String setLabel()

(c) public boolean getState()

(d) (a) and (c)

8.   The public int getSelectedIndex() method returns the index of the selected item; if no item is selected, or if multiple items are selected, it returns

(a) 0

(b) +1

(c) -1

(d) -2

9.   The method public String getSelectedItem() returns the selected item on the list, if no item is selected, or if multiple items are selected, it returns

(a)0

(b) +1

(c) -1

(d) None of the above

10. Each menu item is an instance of

(a) MenuShortcut class

(b) PopupMenu class

(c) MenuItem

(d) None of the above

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   a

2.   d

3.   c

4.   b

5.   c

6.   a

7.   d

8.   c

9.   a

10. c

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.211.106