0% found this document useful (0 votes)
8 views68 pages

Java Unit-Iv

The document outlines the fundamentals of object-oriented programming and Java, covering key concepts such as classes, inheritance, exception handling, and event handling. It details the delegation event model, event sources, listeners, and various event classes like ActionEvent and KeyEvent. Additionally, it provides an overview of Java libraries and interfaces for event handling, along with references for further reading.

Uploaded by

arroju vijetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views68 pages

Java Unit-Iv

The document outlines the fundamentals of object-oriented programming and Java, covering key concepts such as classes, inheritance, exception handling, and event handling. It details the delegation event model, event sources, listeners, and various event classes like ActionEvent and KeyEvent. Additionally, it provides an overview of Java libraries and interfaces for event handling, along with references for further reading.

Uploaded by

arroju vijetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

UNIT - I

Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, History of
Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators,
expressions, control statements, type conversion and casting, simple java program, concepts of classes,
objects, constructors, methods, access control, this keyword, garbage collection, overloading methods
and constructors, parameter passing, recursion, nested and inner classes, exploring string class.

UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final
with inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining,
Creating and Accessing a Package, Understanding CLASSPATH, importing packages, differences
between classes and interfaces, defining an interface, implementing interface, applying interfaces,
variables in interface and extending interfaces. Exploring java.io.

UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of
exception handling, Termination or resumptive models, exception hierarchy, usage of try,
catch, throw, throws and finally, built in exceptions, creating own exception subclasses.
Exploring java.util. Differences between multithreading and multitasking, thread life cycle,
creating threads, thread priorities, synchronizing threads, inter thread communication, thread
groups, daemon threads. Enumerations, autoboxing, annotations, generics.

UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user
interface components- labels, button, canvas, scrollbars, text components, check box,
checkbox groups, choices, lists panels – scrollpane, dialogs, menubar, graphics, layout
manager – layout manager types – border, grid, flow, card and grid bag.

UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXT BOOKS:
1. Java the complete reference, 7th edition, Herbert schildt, TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearson education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John
wiley& sons.
2. An Introduction to OOP, third edition, T. Budd, Pearson education.
3. Introduction to Java programming, Y. Daniel Liang, Pearson education.
4. An introduction to Java programming and object-oriented application development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth
Edition, Pearson Education
7. Object Oriented Programming with Java, R.Buyya, S.T.Selvi, X.Chu, TMH.
8. Java and Object Orientation, an introduction, John Hunt, second edition, Springer.
9. Maurach’s Beginning Java2 JDK 5, SPD.

Event Handling- The Delegation event model


The delegation event model, which defines standard and consistent mechanisms to generateand
process events. Its concept is quite simple: a source generates an event and sends it toone or
more listeners. In this scheme, the listener simply waits until it receives an event.
Once received, the listener processes the event and then returns. The advantage of this designis
that the application logic that processes events is cleanly separated from the user interfacelogic
that generates those events.
In the delegation event model, listeners must register with a source in order to receive anevent
notification. This provides an important benefit: notifications are sent only to listenersthat want
to receive them.
The following sections define events and describe the roles of sources and listeners.

Events:
In the delegation model, an event is an object that describes a state change in a source. It canbe
generated as a consequence of a person interacting with the elements in a graphical userinterface.
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.Many other user operations
could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user
interface.Forexample, an event may be generated when a timer expires, a counter exceeds a
value, asoftware or hardware failure occurs, or an operation is completed. You are free to
defineevents that are appropriate for your application.
Event Sources:
A source is an object that generates an event. This occurs when the internal state of thatobject
changes in some way. Sources may generate more than one type of event.Asourcemust register
listeners in order for the listeners to receive notifications about a specific typeof event. Each type
of event has its own registration method.Here is the general form:
public void addTypeListener(TypeListenerel)
Here, Type is the name of the event and el is a reference to the event listener.
A source must also provide a method that allows a listener to unregister an interest in aspecific
type of event. The general form of such a method is this:
public void removeTypeListener(TypeListenerel)
Here, Type is the name of the event and el is a reference to the event listener.
Event Listeners:
A listener is an object that is notified when an event occurs. It has two majorrequirements.First, it
must have been registered with one or more sources to receivenotifications about specific types
of events. Second, it must implement methods to receiveand process these notifications.The
methods that receive and process events are defined in aset of interfaces found in java.awt.event.
Event Classes:
The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked,oramenu item
is selected. The ActionEvent class defines four integer constants that can be usedto identify any
modifiers associated with an action event: ALT_MASK,CTRL_MASK,META_MASK, and
SHIFT_MASK. In addition, there is an integer constant,ACTION_PERFORMED, which can be
used to identify action events.
ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here, src is a reference to the object that generated this event. The type of the event isspecified
by type, and its command string is cmd. The argument modifiers indicates whichmodifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event wasgenerated. The when
parameter specifies when the event occurred. The thirdconstructor was added by Java 2, version
1.4.
You can obtain the command name for the invoking ActionEvent object by
usingthegetActionCommand( ) method, shown here:
String getActionCommand( )
For example, when a button is pressed, an action event is generated that has a commandname
equal to the label on that button.
The ItemEvent Class
An ItemEvent is generated when a check box or a list item is clicked or when a checkablemenu
item is selected or deselected. (Check boxes and list boxes are described later in thistutorial.)
There are two types of item events, which are identified by the following integerconstants:
DESELECTED The user deselected an item.
SELECTED The user selected an item.
In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED,thatsignifies a
change of state.
ItemEvent has this constructor:
ItemEvent(ItemSelectablesrc, int type, Object entry, int state)
Here, src is a reference to the component that generated this event. For example, this mightbe a
list or choice element. The type of the event is specified by type. The specific item thatgenerated
the item event is passed in entry. The current state of that item is in state.ThegetItem( ) method
can be used to obtain a reference to the item that generated an event. Itssignature is shown here:
Object getItem( )
The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectableobject
that generated an event. Its general form is shown here:
ItemSelectablegetItemSelectable( )
Lists and choices are examples of user interface elements that implement the
ItemSelectableinterface.ThegetStateChange( ) method returns the state change (i.e.,
SELECTEDorDESELECTED) for the event. It is shown here: int
getStateChange( )
The KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key events,which
are identified by these integer constants: KEY_PRESSED,KEY_RELEASED,
andKEY_TYPED. The first two events are generated when any key is pressed or released.
Thelast event occurs only when a character is generated.Remember, not all key presses result
incharacters. For example, pressing the SHIFT key does not generate a character. There aremany
other integer constants that are defined by KeyEvent. For example,VK_0 through
VK_9 and VK_A through VK_Z define the ASCII equivalents of thenumbers and letters. Here
are some others:
VK_ENTER VK_ESCAPE VK_CANCEL VK_UP
VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL
THE JAVA LIBRARY
The VK constants specify virtual key codes and are independent of any modifiers, such
ascontrol, shift, or alt. KeyEvent is a subclass of InputEvent. Here are two of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the event
isspecified by type. The system time at which the key was pressed is passed in when.
Themodifiers argument indicates which modifiers were pressed when this key event
occurred.Thevirtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The
characterequivalent (if one exists) is passed in ch. If no valid character exists, then
chcontainsCHAR_UNDEFINED. For KEY_TYPED events, code will contain
VK_UNDEFINED.
The KeyEvent class defines several methods, but the most commonly used ones
aregetKeyChar( ), which returns the character that was entered, and getKeyCode( ), whichreturns
the key code. Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.
When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following
integerconstants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).
MouseEvent is a subclass of InputEvent. Here is one of its constructors.
MouseEvent(Component src, int type, long when, int modifiers,int x, int y, int
clicks,booleantriggersPopup)
Here, src is a reference to the component that generated the event. The type of the event
isspecified by type. The system time at which the mouse event occurred is passed in when.
Themodifiers argument indicates which modifiers were pressed when a mouse event occurred.
The coordinates of the mouse are passed in x and y. The click count is passed in clicks.
ThetriggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
Java 2, version 1.4 adds a second constructor which also allows the button that caused theevent
to be specified. The most commonly used methods in this class are getX( ) and getY( ).
These return the X and Y coordinates of the mouse when the event occurred. Their formsare
shown here:
int getX( )
int getY( )
The TextEvent Class:
Instances of this class describe text events. These are generated by text fields and text areaswhen
characters are entered by a user or program. TextEvent defines the integer
constantTEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event isspecified
by type.TheTextEvent object does not include the characters currently in the textcomponent that
generated the event. Instead, your program must use other methodsassociated with the text
component to retrieve that information. This operation differs fromother event objects discussed
in this section. For this reason, no methods are discussed herefor the TextEvent class. Think of a
text event notification as a signal to a listener that itshould retrieve information from a specific
text component.
The WindowEvent Class:
There are ten types of window events. The WindowEvent class defines integer constants thatcan
be used to identify them. The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
WindowEvent is a subclass of ComponentEvent. It defines several constructors.
The first is WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type.
Java 2, version 1.4 adds the next three constructors.
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
THE JAVA LIBRARY
Here, other specifies the opposite window when a focus event occurs. The fromStatespecifies the
prior state of the window and toState specifies the new state that the windowwill have when a
window state change occurs.
Sources of Events:
some of the user interface components that can generate the events are listed below
Event Listener Interfaces:
The delegation event model has two parts: sources and listeners. Listeners are created
byimplementing one or more of the interfaces defined by the java.awt.event package. When
anevent occurs, the event source invokes the appropriate method defined by the listener
andprovides an event object as its argument.
The ActionListener Interface:
This interface defines the actionPerformed( ) method that is invoked when an action eventoccurs.
Its general form is shown here:
void actionPerformed(ActionEvent ae)
The AdjustmentListener Interface:
This interface defines the adjustmentValueChanged( ) method that is invoked when anadjustment
event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
The ItemListener Interface:
This interface defines the itemStateChanged( ) method that is invoked when the state of anitem
changes. Its general form is shown here:
void itemStateChanged(ItemEventie)
The KeyListener Interface:
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods areinvoked
when a key is pressed and released, respectively. The keyTyped( ) method isinvoked when a
character has been entered.
For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two keyevents are
generated in sequence: key pressed and released. The general forms of thesemethods are shown
here:
void keyPressed(KeyEventke)
void keyReleased(KeyEventke)
void keyTyped(KeyEventke)
The MouseListener Interface:
This interface defines five methods. If the mouse is pressed and released at the same
point,mouseClicked( ) is invoked. When the mouse enters a component, the
mouseEntered( )method is called. When it leaves, mouseExited( ) is called. The
mousePressed( )andmouseReleased( ) methods are invoked when the mouse is pressed and
released,respectively.The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface:
This interface defines two methods. The mouseDragged( ) method is called multiple times asthe
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse ismoved.
Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
THE JAVA LIBRARY
The WindowListener Interface:
This interface defines seven methods. The windowActivated( ) and
windowDeactivated( )methods are invoked when a window is activated or deactivated,
respectively. If a window isiconified, the windowIconified( ) method is called. When a window
is deiconified,thewindowDeiconified( ) method is called. When a window is opened or
closed,thewindowOpened( ) or windowClosed( ) methods are called, respectively.
ThewindowClosing( ) method is called when a window is being closed. The general forms
ofthese methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
The TextListener Interface:
This interface defines the textChanged( ) method that is invoked when a change occurs in atext
area or text field. Its general form is shown here:
void textChanged(TextEventte)
Handling Mouse Events:
// Demonstrate the mouse event handlers.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MouseEvents extends JFrame implements MouseListener {
JLabel JL;
public MouseEvents()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.CENTER));
JL = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
JL.setFont(f);
JL.setForeground(Color.BLUE);
add(JL);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
JL.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
JL.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
JL.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
JL.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
JL.setText("Mouse Clicked");
}
public static void main(String[] args){
MouseEvents me = new MouseEvents();
}
}

Output:

Handling Keyboard Events:


Type of event generated from keyboard is KeyEvent. Listerner to be registered to
receivenotification is addKeyListener(ref).There is one other requirement that your program
mustmeet before it can process keyboard events: it must request input focus. To do this,
callrequestFocus( ), which is defined by Component. To process the KeyEvent(i.e handle
theevent )the interface to be implemented is KeyListener .This interface defines three methods.
The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed andreleased,
respectively. The keyTyped( ) method is invoked when a character has beenentered.
For example, if a user presses and releases the A key, three events are generated insequence: key
pressed, typed, and released.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener
interface
public class KeyListenerExample extends Frame implements
KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface
where we set the text of the label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface
where we set the text of the label when key is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface
where we set the text of the label when a key is typed
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
// main method
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output:
Adapter Classes:
Java provides a special feature, called an adapter class, that can simplify the creation of
eventhandlers in certain situations. An adapter class provides an empty implementation of
allmethods in an event listener interface. Adapter classes are useful when you want to receiveand
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 extending one of the adapter classesand
implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods,
mouseDragged( )andmouseMoved( ). The signatures of these empty methods are exactly as
defined in theMouseMotionListener interface. If you were interested in only mouse drag events,
then youcould simply extend MouseMotionAdapter and implement mouseDragged( ).
// Demonstrate an adapter class.
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends
MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
// creating the Graphics object and fetching them from the
Frame object using getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
OUTPUT:
The AWT class hierarchy
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
Heavy weight
Look and feel is OS based
Not pure Java based
Applet portability: Web-browser support
Do not support features like icon and tool tip.
The default layout manager for applet: flow and
frame is border layout.

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In order to
place every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
There are four types of containers in Java AWT:
 Window
 Panel
 Frame
 Dialog

Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such as
buttons, labels, and text fields.
Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
Frame: The Frame is the container that contains the title bar and border and can have menu bars.
Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

Changes the visibility of the component, by default


public void setVisible(boolean status)
false.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.

 By extending Frame class (inheritance)


 By creating the object of Frame class (association)
AWT Example by Inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
11.public static void main(String args[]){
First f=new First();
}}
// The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.

AWT Example by Association


import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}

Examples of GUI based Applications


 Automated Teller Machine (ATM)
 Airline Ticketing System
 Information Kiosks at railway stations
 Mobile Applications
 Navigation Systems

AWT UI Elements:

Following is the list of commonly used controls while designed GUI using AWT.

1. Label

A Label object is a component for placing text in a container.

2.Button

This class creates a labeled button.

3.Check Box

A check box is a graphical component that can be in either an on (true) or off (false) state.

4.Check Box Group


The CheckboxGroup class is used to group the set of checkbox.

5.List

The List component presents the user with a scrolling list of text items.

6.Text Field

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

7.Text Area

A TextArea object is a text component that allows for the editing of a multiple lines of text.

8.Choice

A Choice control is used to show pop up menu of choices. Selected choice is shown on the
topof the menu.

9.Canvas

A Canvas control represents a rectangular area where application can draw something or can

receive inputs created by user.

10 Image

An Image control is superclass for all image classes representing graphical images.

11 Scroll Bar

A Scrollbar control represents a scroll bar component in order to enable user to select from
rangeof values.

12 Dialog

A Dialog control represents a top-level window with a title and a border used to take some
formof input from the user.

13 File Dialog

A FileDialog control represents a dialog window from which the user can select a file.
Label

• A label is an object of type Label, and it contains a string which itdisplays.

• Passive controls – do not support any interaction with the user.

• Label defines the following constructors

Label( )

Label(String str) – string is left-justified

Label(String str, int how)

- alignment specified by how

- value of how must be one of the 3 constants

- Label.LEFT, Label.RIGHT, Label.CENTER

• To set or change the text in a label, use the setText( ) method.

void setText(String str)

• To obtain the current label, call getText( )

String getText( )

• To set the alignment of the string within the label, call setAlignment( )

void setAlignment(int how)

• To obtain the current alignment, call getAlignment( )

int getAlignment( )

Creating Label : Label l = new Label(String);

Example:

import java.awt.*;

import java.applet.*;
/*

<applet code = "LabelDemo" width=300 height=200>

</applet>

*/

public class LabelDemo extends Applet

public void init ()

Label one = new Label ("One");

Label two = new Label ("Two");

Label three = new Label ("Three");

add (one);

add (two);

add (three);

OUTPUT:
Button:
The most widely used control is Button. A button is a component that contains a label and that
generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
Button Constructors:
1. Button() throws HeadlessException: It creates an empty button.
2. Button(String str) throws HeadlessException: It creates a button that contains str as a
label.
Button Methods :
1. void setLabel(String str): You can set its label by calling setLabel(). Here, str is the new
Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel() method.
Example to understand AWT Button Control in Java:

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

public class ButtonDemo extends Frame


{
Button b1, b2;
ButtonDemo ()
{
b1 = new Button ("OK");
b2 = new Button ("CANCEL");
this.setLayout (null);
b1.setBounds (100, 100, 80, 40);;
b2.setBounds (200, 100, 80, 40);
this.add (b1);
this.add (b2);
this.setVisible (true);
this.setSize (300, 300);
this.setTitle ("button");
this.addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{
new ButtonDemo ();
}
}
OUTPUT:

Check Box
A checkbox may be a control that’s used to turn an option on or off. It consists of a little box
that will either contain a check or not. There’s a label related to each checkbox that describes
what option the box represents. You modify the state of a checkbox by clicking on.
Checkboxes are often used individually or as a part of a gaggle. Checkboxes are objects of
the Checkbox class.

Creating Checkbox : Checkbox cb = new Checkbox(Label);

Checkbox Constructor

1. Checkbox() throws HeadlessException: Creates a checkbox whose label is initially blank.


The state of the checkbox is unchecked.

2. Checkbox(String str) throws HeadlessException: Creates a checkbox whose label is


specified by str. The state of the checkbox is unchecked.

3. Checkbox(String str, Boolean on) throws HeadlessException: It allows you to line the
initial state of the checkbox. If one is true, the checkbox is initially checked; otherwise,
it’s cleared.

4. Checkbox(String str, Boolean on, CheckboxGroupcbGroup) throws HeadlessException


or Checkbox(String str, CheckboxGroupcbGroup, Boolean on) throws
HeadlessException: It creates a checkbox whose label is specified by str and whose group
is specified by cbGroup. If this checkbox isn’t a part of a gaggle, then cbGroup must be
null. the worth of on determines the initial state of the checkbox.

Methods of Checkbox

1. booleangetState(): To retrieve the present state of a checkbox.

2. void setState(boolean on): To line its state, call setState(). Here, if one is true, the box is
checked. If it’s false, the box is cleared.

3. String getLabel(): you’ll obtain the present label related to a checkbox by calling
getLabel().

4. void setLabel(String str): To line the label, call setLabel(). The string passed in str
becomes the new label related to the invoking checkbox.
Example to understand AWT Checkbox Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="CheckboxDemo" width=250


height=200></applet> */

public class CheckboxDemo extends Applet implements


ItemListener

String msg = "";

Checkbox winXP, winVista, solaris, mac;

public void init ()

winXP = new Checkbox ("Windows XP", null, true);

winVista = new Checkbox ("Windows Vista");

solaris = new Checkbox ("Solaris");

mac = new Checkbox ("Mac OS");

add (winXP);

add (winVista);

add (solaris);

add (mac);
winXP.addItemListener (this);

winVista.addItemListener (this);

solaris.addItemListener (this);

mac.addItemListener (this);

public void itemStateChanged (ItemEventie)

repaint ();

// Display current state of the check boxes.

public void paint (Graphics g)

msg = "Current state: ";

g.drawString (msg, 6, 80);

msg = " Windows XP: " + winXP.getState ();

g.drawString (msg, 6, 100);

msg = " Windows Vista: " + winVista.getState ();

g.drawString (msg, 6, 120);

msg = " Solaris: " + solaris.getState ();

g.drawString (msg, 6, 140);

msg = " Mac OS: " + mac.getState ();


g.drawString (msg, 6, 160);

OUTPUT:

Check Box Group


It is possible to make a group of mutually exclusive checkboxes during which one and just one
checkbox up the group are often checked at anybody time. These checkboxes are often called
radio buttons because they act just like the station selector on a car radio, only one station is
often selected at anybody’s time. To create a group of mutually exclusive checkboxes, you want
to first define the group to which they’re going to belong then specify that group once you
construct the checkboxes. Checkbox groups are objects of the type CheckboxGroup. Only the
default constructor is defined, which creates an empty group.
CreatingRadiobutton:
CheckboxGroupcbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
CheckboxGroup Methods
1. Checkbox getSelectedCheckbox(): You can determine which checkbox in a group is
currently selected by calling getSelectedCheckbox().
2. void setSelectedCheckbox(Checkbox which): You can set a checkbox by calling
setSelectedCheckbox(). Here, is the checkbox that you simply want to be selected. The
previously selected checkbox is going to be turned off.
Example to understand AWT CheckboxGroup Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="CBGroup" width=250 height=200></applet> */

public class RadiobuttonDemo extends Applet implements ItemListener


{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroupcbg;

public void init ()


{
cbg = new CheckboxGroup ();
winXP = new Checkbox ("Windows XP", cbg, true);
winVista = new Checkbox ("Windows Vista", cbg, false);
solaris = new Checkbox ("Solaris", cbg, false);
mac = new Checkbox ("Mac OS", cbg, false);
add (winXP);
add (winVista);
add (solaris);
add (mac);
winXP.addItemListener (this);
winVista.addItemListener (this);
solaris.addItemListener (this);
mac.addItemListener (this);
}

public void itemStateChanged (ItemEventie)


{
repaint ();
}

// Display current state of the check boxes.


public void paint (Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox ().getLabel ();
g.drawString (msg, 6, 100);
}
}
OUTPUT:

List
This component will display a group of items as a drop-down menu from which a user can select
only one item. The List class provides a compact, multiple-choice, scrolling selection list. Unlike
the selection object, which shows only the only selected item within the menu, an inventory
object is often constructed to point out any number of choices within the visible window. It also
can be created to permit multiple selections.
Creating List : List l = new List(int, Boolean);
List Constructor
1. List() throws HeadlessException: It creates a list control that allows only one item to be
selected at any one time.
2. List(int numRows) throws HeadlessException: Here, the value of numRows specifies the
number of entries in the list that will always be visible.
3. List(int numRows, booleanmultipleSelect) throws HeadlessException: If multipleSelect
is true, then the user may select two or more items at a time. If it’s false, then just one
item could also be selected.
Method of Lists
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the items at the
index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It returns a string
containing the name of the item. If more than one item is selected, or if no selection has
been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns the index
of the item. The first item is at index 0. If more than one item is selected, or if no
selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array containing
the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
9. String getItem(int index): It is used to obtain the name associated with the item at the
given index. Here, the index specifies the index of the desired items.
Example to understand AWT List Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ListDemo" width=300 height=180></applet> */

public class ListDemo extends Applet implements ActionListener


{
List os, browser;
String msg = "";

public void init ()


{
os = new List (4, true);
browser = new List (4, false);

// add items to os list


os.add ("Windows XP");
os.add ("Windows Vista");
os.add ("Solaris");
os.add ("Mac OS");

// add items to browser list


browser.add ("Internet Explorer");
browser.add ("Firefox");
browser.add ("Opera");
browser.select (1);

// add lists to window


add (os);
add (browser);

// register to receive action events


os.addActionListener (this);
browser.addActionListener (this);
}

public void actionPerformed (ActionEvent ae)


{
repaint ();
}

// Display current selections.


public void paint (Graphics g)
{
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes ();
for (int i = 0; i<idx.length; i++)
msg += os.getItem (idx[i]) + " ";
g.drawString (msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem ();
g.drawString (msg, 6, 140);
}
}
OUTPUT:
Text Field

The TextField component will allow the user to enter some text. It is used to implement a
single-line text-entry area, usually called an edit control. It also allows the user to enter
strings and edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.

Creating TextField : TextFielftf = new TextField(size);

TextField Constructors

1. TextField() throws HeadlessException: It creates a default textfield.

2. TextField(int numChars) throws HeadlessException: It creates a text field that is


numChars characters wide.

3. TextField(String str) throws HeadlessException: It initializes the text field with the string
contained in str.

4. TextField(String str, int numChars) throws HeadlessException: It initializes a text field


and sets its width.

TextField Methods
1. String getText(): It is used to obtain the string currently contained in the text field.

2. void setText(String str): It is used to set the text. Here, str is the new String.

3. void select(int startIndex, int endIndex): It is used to select a portion of the text under
program control. It selects the characters beginning at startIndex and ending at endIndex-
1.

4. String getSelectedText(): It returns the currently selected text.

5. booleanisEditable(): It is used to determine editability. It returns true if the text may be


changed and false if not.

6. void setEditable(booleancanEdit): It is used to control whether the contents of a text field


may be modified by the user. If canEdit is true, the text may be changed. If it is false, the
text cannot be altered.

7. void setEchoChar(char ch): It is used to disable the echoing of the characters as they are
typed. This method specifies a single character that TextField will display when
characters are entered.

8. booleanechoCharIsSet(): By this method, you can check a text field to see if it is in this
mode.

9. char getEchochar(): It is used to retrieve the echo character.

Example to understand AWT TextFiled Control in Java:

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="TextFieldDemo" width=380 height=150></applet>

*/
public class TextfieldDemo extends Applet implements ActionListener

TextField name, pass;

public void init ()

Label namep = new Label ("Name: ", Label.RIGHT);

Label passp = new Label ("Password: ", Label.RIGHT);

name = new TextField (12);

pass = new TextField (8);

pass.setEchoChar ('?');

add (namep);

add (name);

add (passp);

add (pass);

//register to receive action events

name.addActionListener (this);

pass.addActionListener (this);

//User pressed Enter.

public void actionPerformed (ActionEvent ae)


{

repaint ();

public void paint (Graphics g)

g.drawString ("Name: " + name.getText (), 6, 60);

g.drawString ("Selected text in name: " + name.getSelectedText (), 6, 80);

g.drawString ("Password: " + pass.getText (), 6, 100);

OUTPUT:

Text Area

Sometimes one line of text input isn’t enough for a given task. To handle these situations, the
AWT includes an easy multiline editor called TextArea.
Creating TextArea : TextArea ta = new TextArea();

TextArea Constructor

1. TextArea() throws HeadlessException: It creates a default textarea.

2. TextArea(int numLines, int numChars) throws HeadlessException: It creates a text area


that is numChars characters wide. Here, numLines specifies the height, in lines of the text
area.

3. TextArea(String str) throws HeadlessException: It initializes the text area with the string
contained in str.

4. TextArea(String str, int numLines, int numChars) throws HeadlessException: It initializes


a text field and sets its width. Initial text can be specified by str.

5. TextArea(String str, int numLines, int numChars, int sBars) throws


HeadlessException: Here, you can specify the scroll bars that you want the control to
have. sBars must be one of these values :

1. SCROLLBARS_BOTH

2. SCROLLBARS_NONE

3. SCROLLBARS_HORIZONTAL_ONLY

4. SCROLLBARS_VERTICAL_ONLY

TextArea Methods

TextArea is a subclass of TextComponent. Therefore, it supports


the getText( ), setText( ), getSelectedText( ), select( ),
isEditable( ), and setEditable( ) methods described in the TextField section.

TextArea adds the following methods:

1. void append(String str): It appends the string specified by str to the end of the current
text.

2. void insert(String str, int index): It inserts the string passed in str at the specified index.
3. voidReplaceRange(String str, int startIndex, int endIndex): It is used to replace the text. It
replaces the characters from startIndex to endIndex-1.

Example to understand AWT TextArea Control in Java:

import java.awt.*;

import java.applet.*; /* <applet code="TextAreaDemo" width=300


height=250></applet> */

public class TextAreaDemo extends Applet {

public void init() {

String val = "Java SE 6 is the latest version of the most\n"

+ "widely-used computer language for Internet programming.\n"

+ "Building on a rich heritage, Java has advanced both\n"

+ "the art and science of computer language design.\n\n"

+ "One of the reasons for Java's ongoing success is its\n"

+ "constant, steady rate of evolution. Java has never stood\n"

+ "still. Instead, Java has consistently adapted to the\n"

+ "rapidly changing landscape of the networked world.\n"

+ "Moreover, Java has often led the way, charting the\n" + "course for
others to follow.";

TextArea text = new TextArea(val, 10, 30);

add(text);

}
OUTPUT:

Choice
This component will display a group of times as a drop-down menu from which a user can
select only one item. The choice component is used to create a pop-up list of items from
which the user may choose. Therefore, Choice control is a form of a menu. When it is
inactive, a Choice component takes up only enough space to show the currently selected
item. When the user clicks on a Choice component, the whole list of choices pops up, and a
new selection can be made.

Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added.
2. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
6. void select(String name): It is used to set the currently selected item with a string
that will match a name in the list.
7. String getItem(int index): It is used to obtain the name associated with the item at
the given index. Here, the index specifies the index of the desired items.
Example to understand AWT Choice Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ChoiceDemo" width=300 height=180></applet> */

public class ChoiceDemo extends Applet implements ItemListener


{
Choice os, browser;
String msg = "";

public void init ()


{
os = new Choice ();
browser = new Choice ();

// add items to os list


os.add ("Windows XP");
os.add ("Windows Vista");
os.add ("Solaris");
os.add ("Mac OS");
// add items to browser list
browser.add ("Internet Explorer");
browser.add ("Firefox");
browser.add ("Opera");
browser.add ("Chrome");

// add choice lists to window


add (os);
add (browser);

// register to receive item events


os.addItemListener (this);
browser.addItemListener (this);
}

public void itemStateChanged (ItemEventie)


{
repaint ();
}

// Display current selections.


public void paint (Graphics g)
{
msg = "Current OS: ";
msg += os.getSelectedItem ();
g.drawString (msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem ();
g.drawString (msg, 6, 140);
}
}
OUTPUT:

Canvas
Canvas encapsulates a blank window upon which you can draw in an application or receive
inputs created by the user.
Canvas Constructor:
1. Canvas() : Constructs a new Canvas.
2. Canvas (GraphicsConfiguration config) : Constructs a new Canvas given a
GraphicsConfiguration object.
Canvas Methods:
1. void addNotify(): It is used to create the peer of the canvas.
2. void createBufferStrategy(int numBuffers): It is used to create a new strategy for
multi-buffering on this component.
3. BufferStrategygetBufferStrategy(): It is used to return the BufferStrategy used by
this component.
Example to understand AWT Canvas Control in Java:
import java.awt.*;
import java.awt.event.*;
public class CanvasDemo
{
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public CanvasDemo ()
{
prepareGUI ();
}

public static void main (String[]args)


{
CanvasDemoawtControlDemo = new CanvasDemo ();
awtControlDemo.showCanvasDemo ();
}

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 (WindowEventwindowEvent)
{
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 showCanvasDemo ()


{
headerLabel.setText ("Control in action: Canvas");
controlPanel.add (new MyCanvas ());
mainFrame.setVisible (true);
}

class MyCanvas extends Canvas


{
public MyCanvas ()
{
setBackground (Color.GRAY);
setSize (300, 300);
}

public void paint (Graphics g)


{
Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
}
}
}
OUTPUT:

Image
Image control is superclass for all image classes representing graphical images.
Scroll Bar
Scrollbars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is really a
composite of several individual parts. Each end has an arrow that you simply can click to
get the present value of the scroll bar one unit within the direction of the arrow. The
current value of the scroll bar relative to its minimum and maximum values are indicated
by the slider box for the scroll bar. Scrollbars are encapsulated by the Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();
Scrollbar Constructor
1. Scrollbar() throws HeadlessException: It creates a vertical scrollbar.
2. Scrollbar(int style) throws HeadlessException: It allows you to specify the
orientation of the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar
is created. If a style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException: Here, the initial value of the scroll bar is passed in initialValue.
The number of units represented by the peak of the thumb is passed in thumbSize.
The minimum and maximum values for the scroll bar are specified by min and max.
Scrollbar Methods
1. void setValues(int initialValue, int thumbSize, int min, int max): It is used to set the
parameters of the constructors.
2. int getValue(): It is used to obtain the current value of the scroll bar. It returns the
current setting.
3. void setValue(int newValue): It is used to set the current value. Here, newValue
specifies the new value for the scroll bar. When you set a worth, the slider box inside
the scroll bar is going to be positioned to reflect the new value.
4. int getMaximum(): It is used to retrieve the minimum values. They return the
requested quantity. By default, 1 is the increment added to the scroll bar.
5. int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the
increment subtracted from the scroll bar.
Example to understand AWT Scrollbar Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SBDemo" width=300 height=200></applet> */

public class ScrollbarDemo extends Applet implements AdjustmentListener,


MouseMotionListener
{
String msg = "";
Scrollbar vertSB, horzSB;

public void init ()


{
int width = Integer.parseInt (getParameter ("width"));
int height = Integer.parseInt (getParameter ("height"));
vertSB = new Scrollbar (Scrollbar.VERTICAL, 0, 1, 0, height);
horzSB = new Scrollbar (Scrollbar.HORIZONTAL, 0, 1, 0, width);
add (vertSB);
add (horzSB);

// register to receive adjustment events vertSB.addAdjustmentListener(this);


horzSB.addAdjustmentListener(this);
addMouseMotionListener (this);
}

public void adjustmentValueChanged (AdjustmentEvent ae)


{
repaint ();
}

//Update scroll bars to reflect mouse dragging.


public void mouseDragged (MouseEvent me)
{
int x = me.getX ();
int y = me.getY ();
vertSB.setValue (y);
horzSB.setValue (x);
repaint ();
}

//Necessary for MouseMotionListener


public void mouseMoved (MouseEvent me)
{
}

//Display current value of scroll bars.


public void paint (Graphics g)
{
msg = "Vertical: " + vertSB.getValue ();
msg += ", Horizontal: " + horzSB.getValue ();
g.drawString (msg, 6, 160);

//show current mouse drag position


g.drawString ("*", horzSB.getValue (), vertSB.getValue ());
}
}
OUTPUT:
Dialog
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
AWT Dialog class declaration
public class Dialog extends Window
Example:
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
OUTPUT:

File Dialog

Java's FileDialog class is part of the AWT (Abstract Window Toolkit) package, specifically
designed for creating a file dialog box. This dialog box serves as an intermediary between the
user and the underlying file system, allowing users to browse through directories, select files,
and perform operations on the selected files. With its easy-to-use methods, developers can
integrate file-handling capabilities seamlessly into their Java applications.
Example:

import java.awt.FileDialog;

import java.awt.Frame;

public class FileDialogExample {

public static void main(String[] args) {

// Create a Frame, which is a graphical window to host the FileDialog.

Frame frame = new Frame("File Dialog Example");

// Create a FileDialog with a title, "Select File."

FileDialog fileDialog = new FileDialog(frame, "Select File");

// Display the FileDialog, allowing the user to select a file.

fileDialog.setVisible(true);

// Retrieve the name of the selected file.

String file = fileDialog.getFile();

// Check if a file was selected.

if (file == null) {

// No file was selected; print a message to the console.

System.out.println("No file selected");

} else {

// A file was selected; print the selected file's name to the console.

System.out.println("Selected file: " + file);

}
OUTPUT:

Selected file: example.txt

lists panels – scrollpane,

A ScrollPane in AWT is a container that provides a scrollable view for a component (such as a TextArea or
Panel) when the content is larger than the visible area of the container. It automatically adds horizontal and
vertical scrollbars when required.

import java.awt.*;

public class ScrollPaneExample {

public static void main(String[] args) {

// Create a frame

Frame frame = new Frame("ScrollPane Example");

// Create a large text area

TextArea textArea = new TextArea("This is a large text area. Scroll to see more content.\n".repeat(30));

// Create a ScrollPane and add the text area to it

ScrollPane scrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);

scrollPane.add(textArea);

// Set the size of the ScrollPane (increased height and width)

scrollPane.setSize(400, 400); // Setting width = 400px and height = 400px


// Alternatively, you can use setPreferredSize() for better layout control:

// scrollPane.setPreferredSize(new Dimension(400, 400));

// Add the ScrollPane to the frame

frame.add(scrollPane);

// Set frame size and layout

frame.setSize(500, 500); // You may want to adjust the frame size as well

frame.setLayout(new BorderLayout());

// Make the frame visible

frame.setVisible(true);

// Handle window closing

frame.addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent we) {

System.exit(0);

});

dialogs,
menubar,

graphics,

Layout Manager in Java:

The layout will specify the format or the order in which the components have to be placed on the container.
Layout Manager may be a class or component that’s responsible for rearranging the components on the
container consistent with the required layout. A layout manager automatically arranges your controls within
a window by using some algorithm.

Each Container object features a layout manager related to it. A layout manager is an instance of any class
implementing the LayoutManager interface. The layout manager is about by the setLayout( ) method. If no
call to setLayout( ) is formed, the default layout manager is employed. Whenever a container is resized (or
sized for the primary time), the layout manager is employed to position each of the components within it.

The setLayout( ) method has the subsequent general form: void setLayout(LayoutManager layoutObj)

Here, layoutObj may be a regard to the specified layout manager. If you want to manually disable the layout
manager and position components, pass null for layoutObj. If you do this, you’ll get to determine the form
and position of every component manually, using the setBounds() method defined by Component.

Types of Layout Managers

AWT package provides the following types of Layout Managers:

1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBag Layout

Flow Layout

This layout will display the components from left to right, from top to bottom. The components
will always be displayed in the first line and if the first line is filled, these components are
displayed on the next line automatically.
In this Layout Manager, initially, the container assumes 1 row and 1 column of the window. Depending on
the number of components and size of the window, the number of rows and columns count is decided
dynamically.

Note: If the row contains only one component, then the component is aligned in the center position of that
row.

Creation of Flow Layout

FlowLayout f1 = new FlowLayout();

FlowLayout f1 = new FlowLayout(int align);

FlowLayout f1 = new FlowLayout(int align, int hgap, int vgap);

Example

import java.awt.*;

import javax.swing.*;

public class FlowLayoutDemo

JFrame f;

FlowLayoutDemo ()

f = new JFrame ();

JLabel l1 = new JLabel ("Enter Name");

JTextField tf1 = new JTextField (10);

JButton b1 = new JButton ("SUBMIT");

f.add (l1);
f.add (tf1);

f.add (b1);

f.setLayout (new FlowLayout (FlowLayout.RIGHT));

//setting flow layout of right alignment

f.setSize (300, 300);

f.setVisible (true);

public static void main (String[]args)

new FlowLayoutDemo ();

Output:
Border Layout in Java

This layout will display the components along the border of the container. This layout contains five
locations where the component can be displayed. Locations are North, South, East, west, and Center. The
default region is the center. The above regions are the predefined static constants belonging to the
BorderLayout class. Whenever other regions’ spaces are not in use, automatically container is selected as a
center region default, and the component occupies the surrounding region’s spaces of the window, which
damages the look and feel of the user interface.

Creation of BorderLayout

BorderLayout bl = new BorderLayout();

BorderLayout bl = new BorderLayout(int vgap, int hgap);

Example

import java.awt.*;

public class BorderLayoutDemo

public static void main (String[]args)

Frame f1 = new Frame ();

f1.setSize (250, 250);

Button b1 = new Button ("Button1");

Button b2 = new Button ("Button2");

Button b3 = new Button ("Button3");


Button b4 = new Button ("Button4");

Button b5 = new Button ("Button5");

f1.add (b1, BorderLayout.NORTH);

f1.add (b2, BorderLayout.EAST);

f1.add (b3, BorderLayout.WEST);

f1.add (b4, BorderLayout.SOUTH);

f1.add (b5);

f1.setVisible (true);

Output:

Card Layout in Java

A card layout represents a stack of cards displayed on a container. At a time, only one card can be visible,
each containing only one component.

Creation of Card Layout in Java


CardLayout cl = new CardLayout();

CardLayout cl = new CardLayout(int hgap, int vgap);

To add the components in CardLayout, we use the add method:

add(“Cardname”, Component);

Methods of CardLayout in Java

first(Container): It is used to flip to the first card of the given container.

last(Container): It is used to flip to the last card of the given container.

next(Container): It is used to flip to the next card of the given container.

previous(Container): It is used to flip to the previous card of the given container.

show(Container, cardname): It is used to flip to the specified card with the given name.

Example:

import java.awt.*;

import javax.swing.*;

import javax.swing.JButton;

import java.awt.event.*;

public class CardLayoutDemo extends JFrame implements ActionListener

JButton b1, b2, b3, b4, b5;

CardLayout cl;

Container c;

CardLayoutDemo ()
{

b1 = new JButton ("Button1");

b2 = new JButton ("Button2");

b3 = new JButton ("Button3");

b4 = new JButton ("Button4");

b5 = new JButton ("Button5");

c = this.getContentPane ();

cl = new CardLayout (10, 20);

c.setLayout (cl);

c.add ("Card1", b1);

c.add ("Card2", b2);

c.add ("Card3", b3);

b1.addActionListener (this);

b2.addActionListener (this);

b3.addActionListener (this);

setVisible (true);

setSize (400, 400);

setTitle ("Card Layout");

setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

public void actionPerformed (ActionEvent ae)

cl.next (c);
}

public static void main (String[]args)

new CardLayoutDemo ();

OUTPUT:

Grid Layout in Java

The layout will display the components in the format of rows and columns statically. The container will be
divided into a table of rows and columns. The intersection of a row and column cell and every cell contains
only one component, and all the cells are of equal size. According to Grid Layout Manager, the grid cannot
be empty.

Creation of Grid Layout Manager in Java

GridLayout gl = new GridLayout(int rows, int cols);

GridLayout gl = new GridLayout(int rows, int cols, int vgap, int hgap);
Example

import java.awt.*;

import javax.swing.*;

public class GridLayoutDemo

public static void main (String[]args)

Frame f1 = new Frame ();

f1.setSize (250, 250);

GridLayout ob = new GridLayout (2, 2);

f1.setLayout (ob);

Panel p1 = new Panel ();

Label l1 = new Label ("Enter name");

TextField tf = new TextField (10);

Button b1 = new Button ("Submit");

p1.add (l1);

p1.add (tf);

p1.add (b1);

f1.add (p1);

Panel p2 = new Panel ();

f1.add (p2);

Panel p3 = new Panel ();


f1.add (p3);

Label l2 = new Label ("Welcome to Java");

f1.add (l2);

f1.setVisible (true);

OUTPUT:

Grid Bag Layout in Java

In GridLayout manager, there is no grid control, i.e., inside a grid, we cannot align the component in a
specific position. To overcome this problem, we have an advanced Layout Manager, i.e., Grid Bag Layout
Manager. This layout is the most efficient layout that can be used for displaying components. In this layout,
we can specify the location, size, etc. In this Layout manager, we need to define grid properties or
constraints for each grid. Based on grid properties, the layout manager aligns a component on the grid, and
we can also span multiple grids as per the requirement. Gris properties are defined using the
GridBagConstraints class.

Creation of GridBagLayout: GridBagLayout gbl = new GridBagLayout();


Note: We can specify the location (or) the size with the help of GridBagConstraints.

Properties of GridBagConstraints:

gridx, gridy: For defining x and y coordinate values, i.e., specifying grid location.

gridwidth, grid height: For defining the number of grids to span a document.

fill: Used whenever component size is greater than the area (i.e., VERTICAL or HORIZONTAL).

ipadx, ipady: For defining the width and height of the components, i.e., for increasing component size.

insets: For defining the surrounding space of the component, i.e., top, left, right, bottom.

anchor: Used whenever component size is smaller than area, i.e., where to place in a grid.

FIRST_LINE_START PAGE_START FIRST_LINE_END

LINE_START CENTER LINE_END

LAST_LINE_START PAGE_END LAST_LINE_END

The above format is equal to one grid, so we can specify components in any grid position.

7. weightx, weighty: These are used to determine how to distribute space among columns(weightx) and
among rows(weighty), which is important for specifying resizing behavior.

Example

import java.awt.*;

public class GridBagLayoutDemo

{
public static void main (String[]args)

Frame f1 = new Frame ();

f1.setSize (250, 250);

GridBagLayout gb = new GridBagLayout ();

f1.setLayout (gb);

GridBagConstraints gc = new GridBagConstraints ();

Button b1 = new Button ("Button1");

Button b2 = new Button ("Button2");

Button b3 = new Button ("Button3");

gc.fill = GridBagConstraints.HORIZONTAL;

gc.weightx = 0.5;

gc.weighty = 0.5;

gc.gridx = 0;

gc.gridy = 0;

f1.add (b1, gc);

gc.gridx = 1;

gc.gridy = 0;

f1.add (b2, gc);

gc.gridx = 2;

gc.gridy = 0;

f1.add (b3, gc);

Button b4 = new Button ("Button4");


gc.gridx = 0;

gc.gridy = 1;

gc.gridwidth = 3;

gc.ipady = 40;

Button b5 = new Button ("Button5");

gc.gridx = 2;

gc.gridy = 3;

gc.insets = new Insets (10, 0, 10, 0);

f1.add (b5, gc);

f1.pack ();

f1.setVisible (true);

OUTPUT:

You might also like