Unit 4
Java AWT
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User Interfaces) or Window-
Based Applications in Java. Java AWT is part of the Java Foundation Classes (JFC) that provides a way to build
platform-independent graphical applications.
In this AWT tutorial, you will learn the basics of the AWT, including how to create windows, buttons, labels, and
text fields. We will also learn how to add event listeners to components so that they can respond to user input.
By the end of this tutorial, you will have a good understanding of the AWT and be able to create simple GUIs
in Java.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface (GUI) or Windows-
based Java programs and Java AWT components are platform-dependent, which means they are shown in
accordance with the operating system’s view. AWT is heavyweight, which means that its components consume
resources from the underlying operating system (OS). The [Link] package contains AWT API classes such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Points about Java AWT components
i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of components are platform dependent.
ii.
Why AWT is Platform Independent?
The Java AWT utilizes the native platform subroutine to create API components such as TextField, CheckBox,
and buttons. This results in a different visual format for these components on different platforms such as
Windows, MAC OS, and Unix. The reason for this is that each platform has a distinct view of its native
components. AWT directly calls this native subroutine to create the components, resulting in an AWT application
resembling a Windows application on Windows OS, and a Mac application on the MAC OS. In simpler terms, the
AWT application’s appearance adapts to the platform it is running on.
Understanding how to use BeanFactory is vital for optimizing your application’s performance. To delve deeper
into Java programming, the Java Backend course offers a comprehensive look at various Java concepts and their
applications.
AWT is platform independent even after the AWT components are platform dependent because of the points
mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract API which are
platform independent. Abstract API allows Java to isolate platform-specific details, making code portable across
different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent. Because of this, it ensures
that AWT functionality remains consistent across different environments.
Java AWT Hierarchy
Components: AWT provides various components such as buttons, labels, text fields, checkboxes, etc used for
creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize and group components
in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the containers some of the layout
managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc. using event
listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and write text in
the components of a Java Application.
User Interface Component Model
In addition to the lifecycle description, an overview of JavaServer Faces architecture provides better understanding
of the technology.
JavaServer Faces components are the building blocks of a JavaServer Faces view. A component can be a user
interface (UI) component or a non-UI component.
JavaServer Faces UI components are configurable, reusable elements that compose the user interfaces of JavaServer
Faces applications. A component can be simple, such as a button, or can be compound, such as a table, composed of
multiple components.
JavaServer Faces technology provides a rich, flexible component architecture that includes the following:
A set of [Link] classes for specifying the state and behavior of UI components
A rendering model that defines how to render the components in various ways
A conversion model that defines how to register data converters onto a component
An event and listener model that defines how to handle component events
A validation model that defines how to register validators onto a component
A navigation model that defines page navigation and the sequence in which pages are loaded
This section briefly describes each of these pieces of the component architecture.
User Interface Component Classes
JavaServer Faces technology provides a set of UI component classes and associated behavioral interfaces that
specify all the UI component functionality, such as holding component state, maintaining a reference to objects, and
driving event handling and rendering for a set of standard components.
The component classes are completely extensible, allowing component writers to create their own custom
components. See Chapter 13, Creating Custom UI Components and Other Custom Objects for more information.
The abstract base class for all components is [Link]. JavaServer Faces UI component
classes extend the UIComponentBase class (a subclass of UIComponent), which defines the default state and
behavior of a component. The following set of component classes is included with JavaServer Faces technology:
UIColumn: Represents a single column of data in a UIData component.
UICommand: Represents a control that fires actions when activated.
UIData: Represents a data binding to a collection of data represented by
a [Link] instance.
UIForm: Represents an input form to be presented to the user. Its child components represent (among other
things) the input fields to be included when the form is submitted. This component is analogous to the form tag
in HTML.
UIGraphic: Displays an image.
UIInput: Takes data input from a user. This class is a subclass of UIOutput.
UIMessage: Displays a localized error message.
UIMessages: Displays a set of localized error messages.
UIOutcomeTarget: Displays a hyperlink in the form of a link or a button.
UIOutput: Displays data output on a page.
UIPanel: Manages the layout of its child components.
UIParameter: Represents substitution parameters.
UISelectBoolean: Allows a user to set a boolean value on a control by selecting or deselecting it. This class is a
subclass of the UIInput class.
UISelectItem: Represents a single item in a set of items.
UISelectItems: Represents an entire set of items.
UISelectMany: Allows a user to select multiple items from a group of items. This class is a subclass of
the UIInput class.
UISelectOne: Allows a user to select one item from a group of items. This class is a subclass of
the UIInput class.
Java AWT Tutorial for Beginner & Experienced
Learn the basics of the Abstract Window Toolkit (AWT) in Java, for both beginners and experienced developers.
Java AWT Label
Java AWT Button
Java AWT TextField
Java AWT Checkbox
Java AWT CheckboxGroup
Java AWT Choice
Java AWT List
Java AWT Canvas
AWT Scrollbar
Java AWT MenuItem & Menu
Java AWT PopupMenu
Java AWT Panel
Java AWT Toolkit
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when clicked on. Button Class is used
for creating a labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with show click here as the
value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable
6. Java AWT Choice
The object of the Choice class is used to show a popup menu of choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
8. Java AWT Canvas
Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Create a new canvas
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
Java AWT Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2Scrollbar(intorientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the default value and [mini, maxi] as the
lower and higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows you to create
individual items that can be added to menus. And Menu is a component used to create a dropdown menu that can
contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up a menu that appears when the
user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible
12. Java AWT Panel
Java AWT Panel is a container class used to hold and organize graphical components in a Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
13. Java AWT Toolkit
Java AWT Toolkit class provides us with a platform-independent way to access various system resources and
functionalities. Subclasses of Toolkit are used to bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object
Java JFrame
Thе Java JFramе is an еssеntial componеnt of Java Swing, which is a part of thе Java SWT(Standard Widgеt
Toolkit). JFrame in Java is a class that allows you to crеatе and manage a top-lеvеl window in a Java
application. It sеrvеs as thе main window for GUI-basеd Java applications and providеs a platform-indеpеndеnt
way to crеatе graphical usеr intеrfacеs. In Java JFrame is a part of [Link] package. In this article, we will
learn about Java JFrame.
Constructor of Java JFrame
Constructor Description
This is the default constructor for JFrame. It
JFrame()
creates a new frame with no title
This constructor creates a new frame with the
JFrame(String title)
specified title.
This constructor creates a JFrame that uses the
JFrame(GraphicsConfiguration gc)
specified graphics configuration.
JFrame(String title, GraphicsConfiguration This constructor creates a JFrame with the
Constructor Description
gc) specified title and using the specified graphics
configuration.
This constructor creates a JFrame with the
JFrame(Rectangle bounds)
specified bounds.
This constructor creates a JFrame with the
JFrame(String title, Rectangle bounds)
specified title and bounds.
Methods of Java JFrame
Methods Description
setTitle(String title) Sets the title of the JFrame.
setSize(int width, int height) Sets the size of the JFrame.
Sets the default close operation for the JFrame.
Common options include
setDefaultCloseOperation(int operation) JFrame.EXIT_ON_CLOSE,
JFrame.HIDE_ON_CLOSE, and
JFrame.DO_NOTHING_ON_CLOSE.
Sets the visibility of the JFrame. Pass true to make
setVisible(boolean b)
it visible and false to hide it.
Sets the layout manager for the JFrame, which
setLayout(LayoutManager manager) controls how components are arranged within the
frame.
add(Component comp) Adds a Swing component to the JFrame.
remove(Component comp) Removes a component from the JFrame.
Forces the layout manager to recalculate the layout
validate()
of components within the JFrame.
setResizable(boolean resizable) Controls whether the user can resize the JFrame.
setIconImage(Image image) Sets the icon (image) for the JFrame window.
Java AWT | Color Class
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class creates color by using
the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value where HSB
stands for HUE, SATURATION, BRIcomponents. The value for individual components RGBA ranges from 0 to
255 or 0.0 to 0.1. The value of alpha determines the opacity of the color, where 0 or 0.0 stands fully transparent
and 255 or 1.0 stands opaque.
Constructors of Color Class
1. Color(ColorSpace c, float[] co, float a) : Creates a color in the specified ColorSpace with the color
components specified in the float array and the specified alpha.
2. Color(float r, float g, float b) : creates a opaque color with specified RGB components(values are in range
0.0 – 0.1)
3. Color(float r, float g, float b, float a) : creates a color with specified RGBA components(values are in range
0.0 – 0.1)
4. Color(int rgb): Creates an opaque RGB color with the specified combined RGB value consisting of the red
component in bits 16-23, the green component in bits 8 – 15, and the blue component in bits 0-7.
5. Color(int rgba, boolean b): Creates an sRGB color with the specified combined RGBA value consisting of
the alpha component in bits 24-31, the red component in bits 16 – 23, the green component in bits 8
– 15, and the blue component in bits 0 – 7.
6. Color(int r, int g, int b) : Creates a opaque color with specified RGB components(values are in range 0 –
255)
7. Color(int r, int g, int b, int a) : Creates a color with specified RGBA components(values are in range 0 –
255)
Commonly Used Methods In Color Class
method explanation
creates a new Color that is a brighter version of this
brighter()
Color.
createContext(ColorModel cm, Rectangle r, Rectangle2D creates and returns a PaintContext used to generate
r2d, AffineTransform x, RenderingHints h) a solid color field pattern.
darker() /td> creates a new Color that is a darker version of this
Color.
converts a String to an integer and returns the
decode(String nm)
specified opaque Color.
determines whether another Color object is equal to
equals(Object obj)
this Color.
getAlpha() returns the alpha component in the range 0-255.
getBlue() returns the blue component in the range 0-255 .
method explanation
getColor(String nm) Finds a color in the system properties.
getColor(String nm, Color v) Finds a color in the system properties.
getColor(String nm, int v) Finds a color in the system properties.
returns a float array containing only the color
getColorComponents(ColorSpace cspace, float[]
components of the Color in the ColorSpace
compArray)
specified by the cspace parameter.
returns a float array containing only the color
getColorComponents(float[] compArray) components of the Color, in the ColorSpace of the
Color.
getColorSpace() returns the ColorSpace of this Color.
returns the green component in the range 0-255 in
getGreen()
the default sRGB space.
returns the red component in the range 0-255 in the
getRed()
default sRGB space.
Returns the RGB value representing the color in
getRGB()
the default sRGB ColorModel.
Creates a Color object based on the specified
getHSBColor(float h, float s, float b)
values for the HSB color model.
getTransparency() returns the transparency mode for this Color.
hashCode() computes the hash code for this Color.
HSBtoRGB(float h, float s, float b) Converts the HSB value to RGB value
RGBtoHSB(int r, int g, int b, float[] hsbvals) converts the RGB value to HSB value
Below programs illustrate the Color class in Java AWT :
Program to set the background color of panel using the color specified in the constants of the class
Java
// Java program to set the background color of panel
// using the color specified in the constants
// of the class.
import [Link].*;
import [Link].*;
class color extends JFrame {
// constructor
color()
super("color");
// create a new Color
Color c = [Link];
// create a panel
JPanel p = new JPanel();
// set the background of the frame
// to the specified Color
[Link](c);
setSize(200, 200);
add(p);
show();
// Main Method
public static void main(String args[])
color c = new color();
Output :
Fonts Available in Java AWT
We know that AWT stands for ABSTRACT WINDOW TOOLKIT. For, Example when we want to draw a string
in the AWT in Frame we use the method [Link](String str, int x_coordinate, int
y_coordinate). Now use the Font class for the string to display in the type of font you want. As it is difficult to
remember all the font names we can get the font names that are available in the AWT with the help
of GraphicsEnvironment class in AWT.
After importing the GraphicsEnvironment in the AWT package in java. we need to import
the getLocalGraphicsEnvironment() In the getLocalGraphicsEnvironment() we have to create an object for
that and with the help of the object we have to call the getAvailableFontFamilyNames().
Program to Fetch Font Family Names in the AWT
By using getAvailableFontFamilyNames() you can get the array of all the available fonts in AWT, which have
been displayed on the console.
// Java Program to extract the list of Fonts
import [Link].*;
// Driver class to check available Fonts in AWT
class GFG {
// Main Function
public static void main(String[] args)
{
[Link]("To Know the available font family names");
GraphicsEnvironment ge = [Link]();
[Link]("Getting the font family names");
// Array of all the fonts available in AWT
String fonts[] = [Link]();
// Getting the font family names
for (String i : fonts) {
[Link](i + " ");
}
}
}
Output:
We
Java AWT | BorderLayout Class
BorderLayout is the default layout for the window objects such as JFrame, JWindow, JDialog, JInternalFrame
etc. BorderLayout arranges the components in the five regions. Four sides are referred to as north, south, east, and
west. The middle part is called the center. Each region can contain only one component and is identified by a
corresponding constant as NORTH, SOUTH, EAST, WEST, and CENTER.
Constructors:
1. BorderLayout(): It will construct a new borderlayout with no gaps between the components.
2. BorderLayout(int, int): It will constructs a border layout with the specified gaps between the components.
Commonly Used Methods:
1. toString(): Returns a string which is the representation of the state of border layout.
2. getLayoutAlignmentX(Container parent): Returns the layout alignment along the X-axis.
3. getLayoutAlignmentY(Container parent): It will return the layout alignment along the Y-axis.
4. removeLayoutComponent(Component comp): This method is used to remove the specified component
from the borderlayout.
5. getVgap(): Return the vertical gap between the components.
6. getHgap(): Returns the Horizontal gap between the components.
7. setHgap(int hgap): It is used to set the horizontal gap between the components.
8. setVgap(int vgap): It is used to set the vertical gap between the components.
Below Programs will illustrate the BorderLayout class:
Program 1: The following program creates JButton components in a JFrame, whose instance class is
“BorderLayoutDemo”. We create 5 JButton and then add them to the JFrame by using add() method. We will
set the size and visibility of the frame by using setSize() and setVisible() method respectively. The layout is
set by using the setLayout() method.
Java
// Java program to illustrate the BorderLayout
import [Link].*;
import [Link].*;
import [Link].*;
// class extends JFrame
class BoderLayoutDemo extends JFrame {
BoderLayoutDemo()
{
// Creating Object of Jpanel class
JPanel pa = new JPanel();
// set the layout
[Link](new BorderLayout());
// add a new JButton with name "wel" and it is
// lie top of the container
[Link](new JButton("WelCome"), [Link]);
// add a new JButton with name "come" and it is
// lie button of the container
[Link](new JButton("Geeks"), [Link]);
// add a new JButton with name "Layout" and it is
// lie left of the container
[Link](new JButton("Layout"), [Link]);
// add a new JButton with name "Border" and it is
// lie right of the container
[Link](new JButton("Border"), [Link]);
// add a new JButton with name "hello everybody" and it is
// lie center of the container
[Link](new JButton("GeeksforGeeks"), [Link]);
// add the pa object which refer to the Jpanel
add(pa);
// Function to close the operation of JFrame.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Function to set size of JFrame.
setSize(300, 300);
// Function to set visible status of JFrame.
setVisible(true);
class MainFrame {
// Driver code
public static void main(String[] args)
{
// calling the constructor
new BoderLayoutDemo();
Output:
Event Handling in Java
An event is a change in the state of an object triggered by some action such as Clicking a button, Moving the
cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java, the [Link] package provides
various event classes to handle these actions.
Classification of Events
Events in Java can be broadly classified into two categories based on how they are generated:
1. Foreground Events: Foreground events are the events that require user interaction to generate. Examples of
these events include Button clicks, Scrolling the scrollbar, Moving the cursor, etc.
2. Background Events: Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation completion, etc.
Event Handling Mechanism
Event handling is a mechanism that allows programs to control events and define what should happen when an
event occurs. Java uses the Delegation Event Model to handle events. This model consists of two main
components:
Source: Events are generated from the source. There are various sources like buttons, checkboxes, list, menu-
item, choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
Registering the Source With Listener
To handle events, the source must be registered with a listener. Java provides specific methods for registering
listeners based on the type of event.
Syntax:
addTypeListener()
For example,
addKeyListener() for KeyEvent
addActionListener() for ActionEvent
Event Classes and Listener Interfaces
Java provides a variety of event classes and corresponding listener interfaces. Below table demonstrates the most
commonly used event classes and their associated listener interfaces:
Event Class Listener Interface Description
An event that indicates that a component-defined
ActionEvent ActionListener action occurred like a button click or selecting an
item from the menu-item list.
The adjustment event is emitted by an Adjustable
AdjustmentEvent AdjustmentListener
object like Scrollbar.
An event that indicates that a component moved,
ComponentEvent ComponentListener
the size changed or changed its visibility.
When a component is added to a container (or)
ContainerEvent ContainerListener removed from it, then this event is generated by a
container object.
These are focus-related events, which include
FocusEvent FocusListener
focus, focusin, focusout, and blur.
An event that indicates whether an item was
ItemEvent ItemListener
selected or not.
An event that occurs due to a sequence of
KeyEvent KeyListener
keypresses on the keyboard.
MouseListener & The events that occur due to the user interaction
MouseEvent
MouseMotionListener with the mouse (Pointing Device).
An event that specifies that the mouse wheel was
MouseWheelEvent MouseWheelListener
rotated in a component.
An event that occurs when an object’s text
TextEvent TextListener
changes.
An event which indicates whether a window has
WindowEvent WindowListener
changed its status or not.
Methods in Listener Interfaces
Each listener interface contains specific methods that must be implemented to handle events. Below table
demonstrates the key methods for each interface:
Listener Interface Methods
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
windowActivated()
windowDeactivated()
windowOpened()
WindowListener
windowClosed()
windowClosing()
windowIconified()
Listener Interface Methods
windowDeiconified()