Search...

Friday, November 7, 2014

AWT in JAVA using Java.awt.*; package

  • Abstract Window Toolkit (AWT) is a set of application program interfaces ( API s) used by Java programmers to create graphical user interface ( GUI ) objects, such as buttons, scroll bars, and windows.
  • The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit.
  • The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles

                                                            Component

*Java.awt package contain all GUI Components
  • Component is the superclass of most of the displayable classes defined within the AWT.  Note: it is abstract.
  • MenuComponent is another class which is similar to Component except it is the superclass for all GUI items which can be displayed within a drop-down menu.
  • The Component class defines data and methods which are relevant to all Components
setBounds
setSize
setLocation
setFont
setEnabled
setVisible
setForeground

coloursetBackground  -- colour

The Component class contains the common features to all items which can be displayed in a GUI.  Often, these items are called widgets.  In the AWT, all widgets are components and, as such, inherit all the data and methods of the Component class.


Container
Container is a subclass of Component. (ie. All containers are themselves, Components)Containers contain components.For a component to be placed on the screen, it must be placed within a Container.
The Container class defined all the data and methods necessary for managing groups of Components:
add
getComponent
getMaximumSize
getMinimumSize
getPreferredSize
remove
removeAll
The Container class is an abstract class which encapsulates the logic for managing Components.  Note that Containers are, themselves, Components which means that Containers can be placed within other Containers

Windows and Frames

Generally speaking, the Window class is not used very often.  The Frame class, on the other hand, is used quite extensively for GUI based applications. 

Another subclass of Window, which is not described here, I the Dialog class.  It is used to display Dialog Boxes.

  Dialog Boxes are generally used to convey important information to the user, and must be dismissed by the user before the application can continue. 

 It should be noted that dialog boxes disrupt the flow of an application and can cause great user frustration if not used appropriately.

The Window class defines a top-level Window with no Borders or Menu bar.
Usually used for application splash screens.

Frame defines a top-level Window with Borders and a Menu Bar

Frames are more commonly used than WindowsOnce defined, 
a Frame is a Container which can contain Components 

 Frame aFrame = new Frame(Hello World);  aFrame.setSize(100,100);  aFrame.setLocation(10,10);  aFrame.setVisible(true);


Panels


The Panel class is probably the most important class within the AWT.  Panels can contain Components (which includes other Panels).  It allows the GUI screen to be partitioned into manageable pieces.  Panels should contain Components which are functionally related.  For example, if an application wished to allow the user to input their name, address, phone number and other relevant contact information, it would be good design to place all of the necessary GUI Components on a Panel.  That panel can be then added to and removed from other Containers within the application.


Panel aPanel = new Panel();  aPanel.add(new Button("Ok"));  aPanel.add(new Button("Cancel"));  Frame aFrame = new Frame("Button Test");  aFrame.setSize(100,100);  aFrame.setLocation(10,10);  aFrame.add(aPanel);

Buttons


All GUI systems offer some form of push button.  The Button class in Java represents that functionality.  Buttons are typically single purpose (ie. Their function does not change).

When a button is pressed, it notifies its Listeners.


To be a Listener for a button, an object must implement the ActionListener Interface.  Panel aPanel = new Panel();  Button okButton = new Button("Ok");  Button cancelButton = new Button("Cancel"); 
  aPanel.add(okButton));  aPanel.add(cancelButton));  okButton.addActionListener(controller2);  cancelButton.addActionListener(controller1);

Labels


This class is a Component which displays a single line of text.
Labels are read-only.  

That is, the user cannot click on a label to edit the text it displays.

Text can be aligned within the label
    Label aLabel = new Label("Enter password:");    aLabel.setAlignment(Label.RIGHT);    aPanel.add(aLabel);

List

The List class comes under many names in different GUI systems.  

Lists provide a list of strings which can be selected by the user. 

The programmer may allow the user to select multiple strings within the list. 

This class is a Component which displays a list of Strings.


The list is scrollable, if necessary.


Sometimes called Listbox in other languages.

Lists can be set up to allow single or multiple selections.


The list will return an array indicating which Strings are selected

  List aList = new List();  aList.add("Calgary");  aList.add("Edmonton");  aList.add("Regina");  aList.add("Vancouver");aList.setMultipleMode(true); 

Layouts

Introduction

Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.

Layout Manager

The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.
  • It is very tedious to handle a large number of controls within the container.
  • Oftenly the width and height information of a component is not given when we need to arrange them.
Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.
Following are the interfaces defining functionalities of Layout Managers.
Sr. No.Interface & Description
1LayoutManager
The LayoutManager interface declares those methods which need to be implemented by the class whose object will act as a layout manager.
2LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those classes that know how to layout containers based on layout constraint object.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using AWT.
Sr. No.LayoutManager & Description
1BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.
2CardLayout
The CardLayout object treats each component in the container as a card. Only one card is visible at a time.
3FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4GridLayout
The GridLayout manages the components in form of a rectangular grid.
5GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the component vertically,horizontally or along their baseline without requiring the components of same size.

There are several different LayoutManagers, each of which sizes and positions its Components based on an algorithm:
  • FlowLayout
  • BorderLayout
  • GridLayout
For Windows and Frames, the default LayoutManager is BorderLayout.  For Panels, the default LayoutManager is FlowLayout.

NOTE: If you use a Layout Manager, you can no longer change the size and location of a Component through the setSize and setLocation methods.

Event Handling


Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page are the activities that causes an event to happen.
The events can be broadly classified into two categories:

Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.

Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.


Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model.


The Delegation Event Model has the following key participants namely:


Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object.


Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.

Ex:

 The User clicks the button and the event is generated.

Event object is forwarded to the method of registered listener class.


the method is now get executed and returns.


In order to design a listener class we have to develop some listener interfaces.

These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class.


If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.

In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.



 What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:
  • Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.
  • Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
  • Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object.
  • Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them.

Steps involved in event handling

  • The User clicks the button and the event is generated.
  • Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
  • Event object is forwarded to the method of registered listener class.
  • the method is now get executed and returns.

Points to remember about listener

  • In order to design a listener class we have to develop some listener interfaces.These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class.
  • If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.

Callback Methods

These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the the source must register itself to the listener.

Event Handling Example

Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showEventDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showEventDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener()); 
      submitButton.addActionListener(new ButtonClickListener()); 
      cancelButton.addActionListener(new ButtonClickListener()); 

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         }
         else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked."); 
         }
         else  {
            statusLabel.setText("Cancel Button clicked.");
         }   
      }  
   }
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
Verify the following output
AWT Event Handling





Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as components. Using these components we can create an interactive user interface for an application.
GUI provides result to end user in response to raised events.GUI is entirely based events. For example clicking over a button, closing a window, opening a window, typing something in a textarea etc. These activities are known as events.GUI makes it easier for the end user to use an application. It also makes them interesting.
TermDescription
ComponentComponent is an object having a graphical representation that can be displayed on the screen and that can interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user interface.
ContainerContainer object is a component that can contain other components.Components added to a container are tracked in a list. The order of the list will define the components' front-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.
PanelPanel provides space in which an application can attach any other components, including other panels.
WindowWindow is a rectangular area which is displayed on the screen. In different window we can execute different program and display different data. Window provide us with multitasking environment. A window must have either a frame, dialog, or another window defined as its owner when it's constructed.
FrameA Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. Frame encapsulates window. It and has a title bar, menu bar, borders, and resizing corners.
CanvasCanvas component represents a blank rectangular area of the screen onto which the application can draw. Application can also trap input events from the use from that blank area of Canvas component.



No comments:

Post a Comment