0% found this document useful (0 votes)
183 views87 pages

Java Unit-Iv

The document outlines a comprehensive curriculum on Object-Oriented Programming (OOP) and Java, covering essential topics such as OOP concepts, inheritance, exception handling, multithreading, event handling, applets, and Swing components. It details the Java programming language's features, including data types, classes, methods, and the delegation event model for handling user interactions. Additionally, it provides a list of textbooks and reference materials for further study in Java programming and OOP design.

Uploaded by

anjivadnam
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)
183 views87 pages

Java Unit-Iv

The document outlines a comprehensive curriculum on Object-Oriented Programming (OOP) and Java, covering essential topics such as OOP concepts, inheritance, exception handling, multithreading, event handling, applets, and Swing components. It details the Java programming language's features, including data types, classes, methods, and the delegation event model for handling user interactions. Additionally, it provides a list of textbooks and reference materials for further study in Java programming and OOP design.

Uploaded by

anjivadnam
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/ 87

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.

Sets the size (width and height) of the


public void setSize(int width,int height)
component.

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

Changes the visibility of the component, by


public void setVisible(boolean status)
default 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
}
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();
}}
OUTPUT:

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
top of 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
range of values.

12 Dialog

A Dialog control represents a top-level window with a title and a border used to take some
form of 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 it displays.

• 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.awt.event.*;

public class LabelExample extends Frame {

Label label;

public LabelExample() {

// Setting the title of the Frame

setTitle("AWT Label Example");

// Setting the layout of the Frame

setLayout(new FlowLayout());

// Creating a Label

label = new Label("This is an AWT Label");

// Adding Label to Frame

add(label);

// Setting Frame size and visibility

setSize(300, 200);

setVisible(true);
// Adding Window Listener to close the Frame

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

public static void main(String[] args) {

new LabelExample();

}}

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.*;

public class CheckboxExample

CheckboxExample() {

Frame f = new Frame("Checkbox Example");

Checkbox checkbox1 = new Checkbox("C++");

checkbox1.setBounds(100, 100, 50, 50);

Checkbox checkbox2 = new Checkbox("Java", true);


checkbox2.setBounds(100, 150, 50, 50);

f.add(checkbox1);

f.add(checkbox2);
f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main (String args[])

new CheckboxExample();

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:
import java.awt.*;
import java.awt.event.*;
public class SimpleCheckboxGroupExample extends Frame implements
ItemListener {
CheckboxGroup genderGroup;
Checkbox male, female;
Label label;
public SimpleCheckboxGroupExample() {
setTitle("Gender Selection");
setLayout(new FlowLayout());
setSize(250, 150);
genderGroup = new CheckboxGroup();
male = new Checkbox("Male", genderGroup, false);
female = new Checkbox("Female", genderGroup, false);
add(male);
add(female);
male.addItemListener(this);
female.addItemListener(this);
label = new Label("Select your gender");
add(label);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
@Override
public void itemStateChanged(ItemEvent e) {
Checkbox selectedGender = genderGroup.getSelectedCheckbox();
label.setText("Selected: " + selectedGender.getLabel());
}
public static void main(String[] args) {
new SimpleCheckboxGroupExample();
}
}

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:
import java.awt.*;
import java.awt.event.*;
public class ListExamp
{
ListExamp() {
Frame f = new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500, 100);
Button b = new Button("Show");
b.setBounds(200, 150, 80, 30);
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1);
f.add(l2);
f.add(label);
f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += "\nFramework Selected:";
for(String frame:l2.getSelectedItems()) {
data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExamp();
}
}
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.

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 TextFiled & TextAreaControl in Java:

import java.awt.*;

import java.awt.event.*;

public class TextFieldTextAreaListExample extends Frame implements


ActionListener {

TextField nameField;

List itemList;

TextArea displayArea;

Button showButton;

public TextFieldTextAreaListExample() {

// Set up the Frame

setTitle("AWT TextField, TextArea, and List Example");

setSize(400, 300);

setLayout(new FlowLayout());

// Create and add a TextField for name input

add(new Label("Enter your name:"));

nameField = new TextField(20);

add(nameField);
// Create a List with multiple items and add it to the Frame

itemList = new List(5, true); // multiple selection enabled

itemList.add("Java");

itemList.add("Python");

itemList.add("C++");

itemList.add("JavaScript");

itemList.add("Ruby");

add(new Label("Select your preferred programming languages:"));

add(itemList);

// Create a TextArea to display the results

displayArea = new TextArea(5, 30);

displayArea.setEditable(false); // make it read-only

add(displayArea);

// Create a Button to trigger the display of information

showButton = new Button("Show Selection");

showButton.addActionListener(this);

add(showButton);

// Set Frame visibility and add window listener

setVisible(true);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();
}

});

@Override

public void actionPerformed(ActionEvent e) {

// Get the entered name from TextField

String name = nameField.getText();

// Get selected items from the List

String selectedItems = "";

for (String item : itemList.getSelectedItems()) {

selectedItems += item + " ";

// Display the name and selected items in the TextArea

String displayText = "Name: " + name + "\nPreferred Languages: " +


selectedItems.trim();

displayArea.setText(displayText);

public static void main(String[] args) {

new TextFieldTextAreaListExample();

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:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
//Choice in Java AWT
class MyApp extends Frame{
Choice c;
Button btn;
Label lbl;
public MyApp() {
super("Choice Example");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
c = new Choice();
c.setBounds(10, 50, 100, 100);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
btn = new Button("Show Details");
btn.setBounds(120, 50, 100, 20);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: " + c.getItem(c.getSelectedIndex());
lbl.setText(data);
}
});
lbl = new Label("Empty Label");
lbl.setBounds(10, 70, 300, 30);
add(c);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
public class appchoice {
public static void main(String[] args) {
MyApp frm = new MyApp();
}
}
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:
import java.awt.*;
import java.awt.event.*;
//Canvas in Java AWT
class MyCanvas extends Canvas
{
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
class MyApp extends Frame{
public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
add(new MyCanvas());
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
public class appcanvas {
public static void main(String[] args) {
MyApp frm = new MyApp();
}
}
OUTPUT:
Image
Image control is superclass for all image classes representing graphical images.

Class declaration
Following is the declaration for java.awt.Image class:
public abstract class Image extends Object
Field
Following are the fields for java.awt.Image class:
● protected float accelerationPriority -- Priority for accelerating this image.
● static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling
algorithm.
● static int SCALE_DEFAULT -- Use the default image-scaling algorithm.
● static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority
to scaling speed than smoothness of the scaled image.
● static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the
ReplicateScaleFilter class.
● static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher
priority to image smoothness than scaling speed.
● static Object UndefinedProperty -- The UndefinedProperty object should be returned
whenever a property which was not defined for a particular image is
Class constructors

S.N. Constructor & Description

1 Image()

Class methods

S.N. Method & Description

void flush()
1
Flushes all reconstructable resources being used by this Image object.

2 float getAccelerationPriority()
Returns the current value of the acceleration priority hint.

ImageCapabilities getCapabilities(GraphicsConfiguration gc)


3 Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image
on the specified GraphicsConfiguration.

abstract Graphics getGraphics()


4
Creates a graphics context for drawing to an off-screen image.

abstract int getHeight(ImageObserver observer)


5
Determines the height of the image.

abstract Object getProperty(String name, ImageObserver observer)


6
Gets a property of this image by name.

Image getScaledInstance(int width, int height, int hints)


7
Creates a scaled version of this image.

abstract ImageProducer getSource()


8
Gets the object that produces the pixels for the image.

abstract int getWidth(ImageObserver observer)


9
Determines the width of the image.

void setAccelerationPriority(float priority)


10
Sets a hint for this image about how important acceleration is.

Methods inherited
This class inherits methods from the following classes:
● java.lang.Object
Example
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.showImageDemo();
}
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 showImageDemo(){
headerLabel.setText("Control in action: Image");
controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}
class ImageComponent extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public ImageComponent(String path) {
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(), img.getHeight());
} } }}
OUTPUT:

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:
import java.awt.*;
import java.awt.event.*;
public class TextAreaWithScrollbars extends Frame {
private TextArea textArea;
public TextAreaWithScrollbars() {
// Set up the Frame properties
setTitle("TextArea with Scrollbars Example");
setSize(400, 300);
setLayout(null);
setVisible(true);
// Add a window listener to handle the close operation
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Initialize the TextArea with scrollbars
textArea = new TextArea("Enter your text here...", 10, 30,
TextArea.SCROLLBARS_BOTH);
textArea.setBounds(50, 50, 300, 200); // Position and size
// Add the TextArea to the Frame
add(textArea);
}
public static void main(String[] args) {
new TextAreaWithScrollbars();
} }
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.

EXAMPLE:

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("\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);

});

} }

OUTPUT:

Dialogs:

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.

Unlike Frame, it doesn't have maximize and minimize buttons.


Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.

AWT Dialog class declaration

public class Dialog extends Window

Class constructors

S.N. Constructor & Description

Dialog(Dialog owner)

1 Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an
empty title.

Dialog(Dialog owner, String title)


2
Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title.

Dialog(Dialog owner, String title, boolean modal)


3
Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality.

Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)

4 Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and
GraphicsConfiguration.

Dialog(Frame owner)

5 Constructs an initially invisible, modeless Dialog with the specified owner Frame and an
empty title.

6 Dialog(Frame owner, boolean modal)


Constructs an initially invisible Dialog with the specified owner Frame and modality and an
empty title.

Dialog(Frame owner, String title)


7
Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.

Dialog(Frame owner, String title, boolean modal)


8
Constructs an initially invisible Dialog with the specified owner Frame, title and modality.

Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)

9 Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and
GraphicsConfiguration.

Dialog(Window owner)

10 Constructs an initially invisible, modeless Dialog with the specified owner Window and an
empty title.

Dialog(Window owner, Dialog.ModalityType modalityType)

11 Constructs an initially invisible Dialog with the specified owner Window and modality and an
empty title.

Dialog(Window owner, String title)


12
Constructs an initially invisible, modeless Dialog with the specified owner Window and title.

Dialog(Window owner, String title, Dialog.ModalityType modalityType)


13
Constructs an initially invisible Dialog with the specified owner Window, title and modality.
Dialog(Window owner, String title, Dialog.ModalityType modalityType,
GraphicsConfiguration gc)
14
Constructs an initially invisible Dialog with the specified owner Window, title, modality and
GraphicsConfiguration

Class methods

S.N. Method & Description

void addNotify()
1
Makes this Dialog displayable by connecting it to a native screen resource.

AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Dialog.

Dialog.ModalityType getModalityType()
3
Returns the modality type of this dialog.

String getTitle()
4
Gets the title of the dialog.

void hide()
5
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

boolean isModal()
6
Indicates whether the dialog is modal.

7 boolean isResizable()
Indicates whether this dialog is resizable by the user.

boolean isUndecorated()
8
Indicates whether this dialog is undecorated.

protected String paramString()


9
Returns a string representing the state of this dialog.

void setModal(boolean modal)


10
Specifies whether this dialog should be modal.

void setModalityType(Dialog.ModalityType type)


11
Sets the modality type for this dialog.

void setResizable(boolean resizable)


12
Sets whether this dialog is resizable by the user.

void setTitle(String title)


13
Sets the title of the Dialog.

void setUndecorated(boolean undecorated)


14
Disables or enables decorations for this dialog.

void setVisible(boolean b)
15
Shows or hides this Dialog depending on the value of parameter b.

16 void show()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).

void toBack()

If this Window is visible, sends this Window to the back and may cause it to lose focus or
17
activation if it is the focused or active Window.

Methods inherited

This class inherits methods from the following classes:

● java.awt.Window

● java.awt.Component

● java.lang.Object

EXAMPLE:

import java.awt.*;

import java.awt.event.*;

class MyFrame extends Frame implements ItemListener {

Choice choice;

MyFrame() {

// Set layout for the Frame

setLayout(new FlowLayout());

// Initialize Choice (Dropdown)

choice = new Choice();

// Add items to the dropdown


choice.add("Amaravati");

choice.add("Guntur");

choice.add("Vijayawada");

choice.add("Vizag");

choice.add("Kurnool");

choice.add("Tirupati");

// Add Choice to the Frame

add(choice);

// Add ItemListener to handle item selection

choice.addItemListener(this);

// Handle item selection

public void itemStateChanged(ItemEvent ie) {

// Show a dialog box with the selected item

Dialog dialog = new Dialog(this, "Selected Item", true);

dialog.setLayout(new FlowLayout());

dialog.setSize(200, 100);

dialog.add(new Label("Selected: " +


choice.getSelectedItem()));

Button okButton = new Button("OK");

dialog.add(okButton);

okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

dialog.setVisible(false);

});

dialog.setVisible(true);

} }

public class ChoiceDemo {

public static void main(String[] args) {

MyFrame frame = new MyFrame();

frame.setSize(500, 500);

frame.setVisible(true);

frame.setTitle("AWT Frame Example");

// Close the application on window close

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

} }

Menubar:

Java AWT MenuItem


MenuItem is a class that represents a simple labeled menu item within a menu. It can be added to
a menu using the Menu.add(MenuItem mi) method.

Syntax of Class Declaration MenuItem:

public class MenuItem extends MenuComponent implements Accessible

Methods of the MenuItem Class

Method Description

Constructs a new MenuItem with the specified


public MenuItem(String label) label.

public String getLabel() Returns the label of the menu item.

Sets the label of the menu item to the specified


public void setLabel(String label) string.

public void
Adds an action listener to the menu item.
addActionListener(ActionListener l)

Java AWT Menu Class

The Java AWT Menu class represents a pop-up menu component in a graphical user interface
(GUI) that can contain a collection of MenuItem objects. It provides a way to create and manage
menus in Java AWT applications.

Syntax of Class Declaration of Menu


public class Menu extends MenuItem

Methods of the Menu Class

Method Description

public Menu(String label) Constructs a new menu with the specified label.

public void add(MenuItem mi) Adds the specified menu item to the menu.

public void addSeparator() Adds a separator between menu items within the menu.

public MenuShortcut getShortcut() Returns the menu shortcut key associated with this menu.

Example:

import java.awt.*;

import java.awt.event.*;

//Menu Bar in AWT

class MyApp extends Frame {

public MyApp() {

super("Menu Bar Example");

setSize(1000, 600);// w,h

setLayout(null);

setVisible(true);
MenuBar m=new MenuBar();

Menu menu=new Menu("Menu");

Menu submenu=new Menu("Sub Menu");

MenuItem i1=new MenuItem("Mango");

MenuItem i2=new MenuItem("Apple");

MenuItem i3=new MenuItem("Grapes");

MenuItem i4=new MenuItem("Guva");

MenuItem i5=new MenuItem("Banana");

menu.add(i1);

menu.add(i2);

menu.add(i3);

submenu.add(i4);

submenu.add(i5);

menu.add(submenu);

m.add(menu);

setMenuBar(m);

// Close Button Code

this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

} }
public class appmenu {

public static void main(String[] args) {

MyApp frm = new MyApp();

} }

OUTPUT:

Graphics:

The Graphics class is the abstract super class for all graphics contexts which allow an application
to draw onto components that can be realized on various devices, or onto off-screen images as
well.

Class declaration

public abstract class Graphics extends Object

Class constructors

S.N. Constructor & Description

Graphics() ()
1
Constructs a new Graphics object.

Class methods

S.N. Method & Description


abstract void clearRect(int x, int y, int width, int height)

1 Clears the specified rectangle by filling it with the background color of the current drawing
surface.

abstract void clipRect(int x, int y, int width, int height)


2
Intersects the current clip with the specified rectangle.

abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
3
Copies an area of the component by a distance specified by dx and dy.

abstract Graphics create()


4
Creates a new Graphics object that is a copy of this Graphics object.

Graphics create(int x, int y, int width, int height)

5 Creates a new Graphics object based on this Graphics object, but with a new translation and
clip area.

abstract void dispose()


6
Disposes of this graphics context and releases any system resources that it is using.

void draw3DRect(int x, int y, int width, int height, boolean raised)


7
Draws a 3-D highlighted outline of the specified rectangle.

abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
8
Draws the outline of a circular or elliptical arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x, int y)

9 Draws the text given by the specified byte array, using this graphics context's current font and
color.

void drawChars(char[] data, int offset, int length, int x, int y)

10 Draws the text given by the specified character array, using this graphics context's current
font and color.

abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver

11 observer)

Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)


12
Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor,
ImageObserver observer)
13
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.

abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
14
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.

15 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, ImageObserver observer)
16
Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.

abstract void drawLine(int x1, int y1, int x2, int y2)

17 Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics
context's coordinate system.

abstract void drawOval(int x, int y, int width, int height)


18
Draws the outline of an oval.

abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)


19
Draws a closed polygon defined by arrays of x and y coordinates.

void drawPolygon(Polygon p)
20
Draws the outline of a polygon defined by the specified Polygon object.

abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)


21
Draws a sequence of connected lines defined by arrays of x and y coordinates.

void drawRect(int x, int y, int width, int height)


22
Draws the outline of the specified rectangle.

23 abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.

abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

24 Renders the text of the specified iterator applying its attributes in accordance with the
specification of the TextAttribute class.

abstract void drawString(String str, int x, int y)

25 Draws the text given by the specified string, using this graphics context's current font and
color.

void fill3DRect(int x, int y, int width, int height, boolean raised)


26
Paints a 3-D highlighted rectangle filled with the current color.

abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
27
Fills a circular or elliptical arc covering the specified rectangle.

abstract void fillOval(int x, int y, int width, int height)


28
Fills an oval bounded by the specified rectangle with the current color.

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)


29
Fills a closed polygon defined by arrays of x and y coordinates.

void fillPolygon(Polygon p)

30 Fills the polygon defined by the specified Polygon object with the graphics context's current
color.

31 abstract void fillRect(int x, int y, int width, int height)


Fills the specified rectangle.

abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int

32 arcHeight)

Fills the specified rounded corner rectangle with the current color.

void finalize()
33
Disposes of this graphics context once it is no longer referenced.

abstract Shape getClip()


34
Gets the current clipping area.

abstract Rectangle getClipBounds()


35
Returns the bounding rectangle of the current clipping area.

Rectangle getClipBounds(Rectangle r)
36
Returns the bounding rectangle of the current clipping area.

Rectangle getClipRect()
37
Deprecated. As of JDK version 1.1, replaced by getClipBounds().

abstract Color getColor()


38
Gets this graphics context's current color.

abstract Font getFont()


39
Gets the current font.

40 FontMetrics getFontMetrics()
Gets the font metrics of the current font.

abstract FontMetrics getFontMetrics(Font f)


41
Gets the font metrics for the specified font.

boolean hitClip(int x, int y, int width, int height)


42
Returns true if the specified rectangular area might intersect the current clipping area.

abstract void setClip(int x, int y, int width, int height)


43
Sets the current clip to the rectangle specified by the given coordinates.

abstract void setClip(Shape clip)


44
Sets the current clipping area to an arbitrary clip shape.

abstract void setColor(Color c)


45
Sets this graphics context's current color to the specified color.

abstract void setFont(Font font)


46
Sets this graphics context's font to the specified font.

abstract void setPaintMode()

47 Sets the paint mode of this graphics context to overwrite the destination with this graphics
context's current color.

48 abstract void setXORMode(Color c1)

Sets the paint mode of this graphics context to alternate between this graphics context's
current color and the new specified color.

String toString()
49
Returns a String object representing this Graphics object's value.

abstract void translate(int x, int y)

50 Translates the origin of the graphics context to the point (x, y) in the current coordinate
system.

Methods inherited

This class inherits methods from the following classes:

● java.lang.Object

Example:

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {

public AWTGraphicsDemo(){

super("Java AWT Examples");

prepareGUI();

public static void main(String[] args){


AWTGraphicsDemo awtGraphicsDemo = new
AWTGraphicsDemo();

awtGraphicsDemo.setVisible(true);

private void prepareGUI(){

setSize(400,400);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

@Override

public void paint(Graphics g) {

g.drawRect(50, 60, 50, 20);

g.drawRoundRect(50, 90, 50, 20, 10, 10);

g.setColor(Color.GREEN);

Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 24);

g.setFont(font);

g.drawString("Hello JAVA", 50, 150);

} }

OUTPUT:
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 java.awt.event.*;

public class FlowLayoutDemo {

Frame f;

FlowLayoutDemo() {

// Create a Frame

f = new Frame();
// Create AWT components

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

TextField tf1 = new TextField(10);

Button b1 = new Button("SUBMIT");

// Add components to the Frame

f.add(l1);

f.add(tf1);

f.add(b1);

// Set the layout to FlowLayout with right alignment

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

// Set Frame properties

f.setSize(300, 300);

f.setVisible(true);

// Add Window Listener to close the application

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

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 java.awt.event.*;

import java.awt.event.ActionListener;

public class CardLayoutDemo extends Frame implements ActionListener


{

Button b1, b2, b3, b4, b5;


CardLayout cl;

CardLayoutDemo() {

// Initialize buttons

b1 = new Button("Button1");

b2 = new Button("Button2");

b3 = new Button("Button3");

b4 = new Button("Button4");

b5 = new Button("Button5");

// Set up the CardLayout

cl = new CardLayout(10, 20); // Horizontal and vertical gap

setLayout(cl);

// Add buttons to the layout

add("Card1", b1);

add("Card2", b2);

add("Card3", b3);

add("Card4", b4);

add("Card5", b5);

// Add ActionListeners for the buttons

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);
// Frame properties

setSize(400, 400);

setTitle("Card Layout (AWT)");

setVisible(true);

// Close operation

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

// Handle button clicks

public void actionPerformed(ActionEvent ae) {

cl.next(this); // Move to the next card

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 java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class GridLayoutExampleee {

Frame frameObj;

// Constructor

GridLayoutExampleee() {

frameObj = new Frame("Grid Layout Example");

// Creating 9 buttons
Button btn1 = new Button("1");

Button btn2 = new Button("2");

Button btn3 = new Button("3");

Button btn4 = new Button("4");

Button btn5 = new Button("5");

Button btn6 = new Button("6");

Button btn7 = new Button("7");

Button btn8 = new Button("8");

Button btn9 = new Button("9");

// Setting the layout to GridLayout

frameObj.setLayout(new GridLayout(3, 3)); // 3 rows and 3


columns

// Adding buttons to the frame

frameObj.add(btn1);

frameObj.add(btn2);

frameObj.add(btn3);

frameObj.add(btn4);

frameObj.add(btn5);

frameObj.add(btn6);

frameObj.add(btn7);

frameObj.add(btn8);

frameObj.add(btn9);
// Setting frame size and visibility

frameObj.setSize(300, 300);

frameObj.setVisible(true);

// Close the application when the window is closed

frameObj.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

// Main method

public static void main(String[] args) {

new GridLayoutExampleee();

} }

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.
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 GridBagLayoutExampleee extends Frame {

public static void main(String[] args) {

GridBagLayoutExampleee a = new GridBagLayoutExampleee();

public GridBagLayoutExampleee() {

// Creating the GridBagLayout and GridBagConstraints objects

GridBagLayout grid = new GridBagLayout();

GridBagConstraints gbc = new GridBagConstraints();

// Setting layout manager for the frame

setLayout(grid);

setTitle("GridBag Layout Example");

// First button, top left

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0;

gbc.gridy = 0;

add(new Button("Button One"), gbc);

// Second button, top right

gbc.gridx = 1;
gbc.gridy = 0;

add(new Button("Button Two"), gbc);

// Third button, bottom left with extra vertical padding

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.ipady = 20; // Increase height

gbc.gridx = 0;

gbc.gridy = 1;

add(new Button("Button Three"), gbc);

// Fourth button, bottom right

gbc.gridx = 1;

gbc.gridy = 1;

add(new Button("Button Four"), gbc);

// Fifth button, spanning both columns

gbc.gridx = 0;

gbc.gridy = 2;

gbc.gridwidth = 2; // Span across 2 columns

add(new Button("Button Five"), gbc);

// Setting frame size and making it visible

setSize(300, 300);

setVisible(true);

// Add window listener to handle the close operation

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

System.exit(0);

});

} }

OUTPUT:

You might also like