Dept. of CSE, VVIT Dept. of CSE, VVIT

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

[JAVA] Dept. of CSE, VVIT [JAVA] Dept.

of CSE, VVIT

AWT Dimension Specifies the dimensions of an object. The width is stored


(Abstract Window Toolkit) in width, and the height is stored in height.
Event Encapsulates events.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT
contains numerous classes and methods that allow you to create and manage windows. Although the main EventQueue Queues events.
FileDialog Creates a window from which a file can be selected.
purpose of the AWT is to support applet windows, it can also be used to create stand-alone windows that
FlowLayout The flow layout manager. Flow layout positions
run in a GUI environment, such as Windows. AWT features include:
components left to right, top to bottom.
A set of native user interface components Font Encapsulates a type font.
A robust event-handling model FontMetrics Encapsulates various information related to a font. This
Graphics and imaging tools, including shape, color, and font classes information helps you display text in a window.
Layout managers, for flexible window layouts that don't depend on a particular Frame Creates a standard window that has a title bar, resize
window size or screen resolution corners, and a menu bar.
Data transfer classes, for cut-and-paste through the native platform clipboard. Graphics Encapsulates the graphics context. This context is used
by the various output methods to display output in a
The Abstract Window Toolkit (AWT) provides support for applets. The AWT contains numerous classes Window.
and methods that allow you to create and manage windows. Although the main purpose of the AWT is to GraphicsDevice Describes a graphics device such as a screen or printer.
support applet windows, it can also be used to create stand-alone windows that run in a GUI environment, GraphicsEnvironment Describes the collection of available Font and
such as Windows. GraphicsDevice objects.
GridBagLayout The grid bag layout manager. Grid bag layout displays
AWT Classes: The AWT classes are contained in the java.awt components subject to the constraints specified by
Fortunately, because it is logically organized in a top-down, hierarchical fashion. The following is the list of GridBagConstraints.
AWT classes: GridLayout The grid layout manager. Grid layout displays
Components in a two-dimensional grid.
Class Description Image Encapsulates graphical images.

AWTEvent Encapsulates AWT events.


AWTEventMulticaster Dispatches events to multiple listeners. Window Fundamentals
BorderLayout The border layout manager. Border layouts use five
Components : North, South, East, West, and Center. The AWT defines windows according to a class hierarchy that adds functionality and specificity with each
Button Creates a push button control. level. The two most common windows are those derived from Panel, which is used by applets, and those
Canvas A blank, semantics-free window. derived from Frame, which creates a standard window. Much of the functionality of these windows is
CardLayout The card layout manager. Card layouts emulate index derived from their parent classes. Thus, a description of the class hierarchies relating to these two classes is
cards. Only the one on top is showing. fundamental to their understanding. The following diagram shows the class hierarchy for Panel and Frame.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item. Component: At the top of the AWT hierarchy is the Component class. Component is an abstract class that
Choice Creates a pop-up list. encapsulates all of the attributes of a visual component. All user interface elements that are displayed on
Color Manages colors in a portable, platform-independent the screen and that interact with the user are subclasses of Component. It defines over a hundred public
Fashion. methods that are responsible for managing events, such as mouse and keyboard input, positioning and
Component An abstract super class for various AWT components. sizing the window, and repainting. A Component object is responsible for remembering the current
Container Subclass of Component that can hold other components. foreground and background colors and the currently selected text font.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

Container: Containers allow us to organize components into manageable groups which is extremely A is an object that generates an event. This occurs when the internal state of that object changes in
important in order to create a good user interface. A component in the AWT can only be used if it is held some way. Sources may generate more than one type of event. A source must register listeners in order for
in a container. A component without a container is like a door without a house. This section covers panels. the listeners to receive notifications about a specific type of event. Each type of event has its own
(Applets are a subclass of panels.), frames, and dialog boxes (which are both subclasses of windows). The registration method.
Container class is a subclass of Component. A container is responsible for laying out (that is, positioning)
any components that it contains. It does this through the use of various layout managers. The Panel class is Here is the general form: public void add Listener( Listener )
a concrete subclass of Container ny new methods; it simply implements Container.
Here, is the name of the event and is a reference to the event listener.
Panel: A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the super
class for Applet. When screen output is directed to an Applet, it is drawn on the surface of a Panel object. For example,
In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why you the method that registers a keyboard event listener is called addKeyListener( ).
see these items when an Applet is run inside a browser. When you run an applet using an applet viewer, The method that registers a mouse motion listener is called addMouseMotionListener( ).
the applet viewer provides the title and border.
Event Listeners
A is an object that is notified when an event occurs. It has two major requirements. First, it must
EVENT HANDLING have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.
In Graphical User Interface based applications, the programs are completely based on event driven
programming where the user has more flexibility to work with. Users can interact with the applications in To sum up, here's an overview of how event handling in the AWT works.
any form. In Java there is a specific approach where event driven programs may be organized.
A listener object is an instance of a class that implements a special interface called (naturally
Delegation Event Model: enough) a listener interface.
An event source is an object that can register listener objects and send them event objects.
The modern approach to handling events is based on the , which defines standard The event source sends out event objects to all registered listeners when that event occurs.
and consistent mechanisms to generate and process events. Its concept is quite simple: a generates an The listener objects will then use the information in the event object to determine their reaction to
event and sends it to one or more . In this scheme, the listener simply waits until it receives an the event.
event. Once received, the listener processes the event and then returns. The advantage of this design is that
the application logic that processes events is cleanly separated from the user interface logic that generates You register the listener object with the source object by using lines of code that follow the model:
those events. An
eventSourceObject addEventListener
code.
In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want to receive
them. The main components in event handling through JAVA are:
Events
Event Sources
Event Listeners
Events
In the delegation model, an is an object that describes a state change in a source. It can be generated
as a consequence of a person interacting with the elements in a graphical user interface. Some of the
activities that cause events to be generated are pressing a button, entering a character via the keyboard,
selecting an item in a list, and clicking the mouse.

Event Sources
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

The following is the list of AWT Event Classes: public void adjustmentValueChanged(AdjustmentEvent ae)
{

}
ComponentListener: Defines four methods to recognize when a component is hidden, moved, resized, or
shown.

ContainerListener: Defines two methods to recognize when a component is added to or removed from a
container.

FocusListener: Defines two methods to recognize when a component gains or loses keyboard focus. The
methods to be implemented are:

void focusGained(FocusEvent fe)


void focusLost(FocusEvent fe)

ItemListener: Defines one method to recognize when the state of an item changes.

Public void itemStateChanged(ItemEvent e)


{

}
KeyListener: Defines three methods to recognize when a key is pressed, released, or typed. The methods to
be implemented are:

Public void keyPressed(KeyEvent e) {}


There are eleven listener interfaces altogether in the java.awt.event package: Public void keyReleased(KeyEvent e) {}
Public void keyTyped(KeyEvent e) {}
ActionListener KeyListener AdjustmentListener MouseListener
ComponentListener MouseMotionListener ContainerListener TextListener MouseListener: Defines five methods to recognize when the mouse is clicked, enters a component, exits a
FocusListener WindowListener ItemListener component, is pressed, or is released. The methods to be implemented are:
Public void mousePressed(MouseEvent e){ }
Interface Description public void mouseReleased(MouseEvent e) { }
Public void mouseClicked(MouseEvent e) { }
ActionListener: Defines one method to receive action events. The method to be implemented is: Public void mouseEntered(MouseEvent e){ }
Public void mouseExited(MouseEvent e){ }
public void actionPerformed(ActionEvent ae)
{ MouseMotionListener: Defines two methods to recognize when the mouse is dragged or moved. The
methods to be implemented are:
}
Public void mouseDragged(MouseEvent e){ }
AdjustmentListener: Defines one method to receive adjustment events. The method to be implemented is: Public void mouseMoved(MouseEvent e){ }
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

MouseWheelListener: Defines one method to recognize when the mouse wheel is moved. Adapter classes:

public void mouseWheelMoved(MouseWheelEvent e){ } Java provides a special feature, called an , which can simplify the creation of event handlers in
certain situations. An adapter class provides an empty implementation of all methods in an event listener
TextListener: Defines one method to recognize when a text value changes. interface. Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface. You can define a new class to act as an event listener by
void textChanged(TextEvent te) extending one of the adapter classes and implementing only those events in which you are interested.

WindowFocusListener: Defines two methods to recognize when a window gains or losses input focus. The following is the list of adapter classes in java.awt package:

WindowListener: Defines seven methods to recognize when a window is activated, closed, deactivated, Adapter Class Listener
deiconified, iconified, opened, or quit. The methods to be implemented are:
ComponentAdapter ComponentListener
void windowActivated(WindowEvent we) ContainerAdapter ContainerListener
void windowClosed(WindowEvent we) FocusAdapter FocusListener
void windowClosing(WindowEvent we) KeyAdapter KeyListener
void windowDeactivated(WindowEvent we) MouseAdapter M ouseListener
void windowDeiconified(WindowEvent we) MouseMotionAdapter MouseMotionListener
void windowIconified(WindowEvent we) WindowAdapter WindowListener
void windowOpened(WindowEvent we)
An adapter class can be implemented either an inner class or anonymous inner class.
The following is the list of event sources:
Ex1:
Event Source Description
import java.awt.*;
Button Generates action events when the button is pressed. import java.awt.event.*;
Checkbox Generates item events when the check box is selected or deselected. public class WindowInnerDemo extends Frame
Choice Generates item events when the choice is changed. {
List Generates action events when an item is double-clicked; generates item events public WindowInnerDemo()
when an item is selected or deselected. {
Menu Item Generates action events when a menu item is selected; addWindowListener(new MyWindowAdapter());
Scrollbar Generates adjustment events when the scroll bar is manipulated. }
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed, deactivated, class MyWindowAdapter extends WindowAdapter
deiconified, iconified, opened, or quit. {
public void windowClosing(WindowEvent me)
{
System.exit(0);
}
}
public static void main(String args[])
{
WindowInnerDemo w =new WindowInnerDemo();
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

w.setVisible(true); FRAMES
w.setSize(300,300);
} A frame is window in Java. It is a subclass of Window and has a title bar, menu bar, borders, and resizing
} corners. When a Frame window is created by a program rather than an Applet, a normal window is
created.
Ex2:
The hierarchy of frames is given below:
import java.applet.*;
import java.awt.*; Object Component Container Window Frame
import java.awt.event.*;
public class MouseInnerDemo extends Applet The Frame class is a subclass of Container class.
{ Container class objects may have other components (e.g. Buttons) added to them using the add method.
public void init() A typical Java GUI will create and display one or more frames.
{ To make a frame visible the message setVisbible(true) must be sent to the frame.
setBackground(Color.green);
addMouseListener(new MyMouseAdapter()); Ex:
}
import java.awt.*;
class MyMouseAdapter extends MouseAdapter public class ButtonDemo extends Frame
{ {
public void mousePressed(MouseEvent me) Button redButton, blueButton;
{ public ButttonDemo()
setBackground(Color.red); {
repaint();
}
public void mouseReleased(MouseEvent me) setLayout(new Flowlayout());
{ add(redButton);
setBackground(Color.green); add(blueButton);
repaint(); pack();
} }
} public static void main(String args[])
} {
ButtonDemo b = new ButtonDemo();
b.setVisible(true);
b.setSize(300,400);

}
}

Frames using Threads:

import java.awt.*;
import java.awt.event.*;
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

public class ThreadAWT extends Frame implements Runnable,ActionListener tg.suspend();


{
int cnt=0; if(ae.getSource()==btnresume)
Panel p1; tg.resume();
TextField tf1;
Button btnsuspend; if(ae.getSource()==btnstart)
Button btnresume; tg.start();
Button btnstart;
Button btnstop; if(ae.getSource()==btnstop)
Thread tg; tg.stop();
public ThreadAWT() }
{ public static void main(String args[])
tg=new Thread(this); {
p1=new Panel(); ThreadAWT ta=new ThreadAWT();
tf1=new TextField(10); }
btnsuspend=new Button("Suspend"); }
btnresume=new Button("Resume");
btnstart=new Button("Start"); Layout Managers:
btnstop=new Button("Stop");
p1.add(tf1); All of the components that we have shown so far have been positioned by the default layout manager. A
p1.add(btnsuspend); automatically positions components within a container. Thus the appearance of the
p1.add(btnresume); window can be changed according to the user wish. Java supports different layouts in terms of classes. The
p1.add(btnstart); following is the list of layout manager classes:
p1.add(btnstop);
add(p1); Each Container object has a layout manager associated with it.
btnsuspend.addActionListener(this); A layout manager is an instance of any class that implements the LayoutManager interface.
btnresume.addActionListener(this); The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the
btnstart.addActionListener(this); default layout manager is used.
btnstop.addActionListener(this); Whenever a container is resized (or sized for the first time), the layout manager is used to position
pack(); each of the components within it.
setVisible(true); Each layout manager keeps track of a list of components that are stored by their names.
}
public void run() The setLayout( ) method has the following general form:
{
while(true) void setLayout(LayoutManager layoutObj)
{
cnt++; Types of Layout managers:
tf1.setText(Integer.toString(cnt));
} FlowLayout
} Default frame layout
public void actionPerformed(ActionEvent ae) Components are placed on new line only when needed.
{ -- FlowLayout implements a simple layout style, which is similar to how words flow in a text
if(ae.getSource()==btnsuspend) editor.
[JAVA] Dept. of CSE, VVIT [JAVA] Dept. of CSE, VVIT

-- Components are laid out from the upper-left corner, left to right and top to bottom

GridLayout
Frame is declared as a grid of fixed size (e.g. two rows and three columns)
Components are placed in the grid left to right and top to bottom.

CardLayout

The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout
can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given
time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon
user input. You can prepare the other layouts and have them hidden, ready to be activated when needed.

BorderLayout
Frame is divided into north, south, east, west, and center
Components are placed by the programmer in the desired location using the add method
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
B orderLayout.SOUTH Box Layout: The BoxLayout class puts components in a single row or column. It respects the components'
BorderLayout.EAST requested maximum sizes and also lets you align components.
B orderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
void add(Component compObj, Object region);

GridbagLayout
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid
of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and
grid columns can have different widths.

You might also like