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.
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.
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.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine
for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix. The
reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
Types of Containers
Container: A Container is a subclass of Component; it has methods that allow other
components to be nested in it. A container is responsible for laying out (that is positioning) any
component that it contains. It does this with various layout managers.
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container. A window represents a rectangular area
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components. Panel class
is a subclass of Container and is a super class of Applet.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application. It is a subclass of Window and it has title
bar, menu bar, border and resizing windows.
Event Model:
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by 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.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
[Link]
1. // importing Java AWT class
2. import [Link].*;
3.
4. // extending Frame class to our class AWTExample1
5. public class AWTExample1 extends Frame {
6.
7. // initializing using constructor
8. AWTExample1() {
9.
10. // creating a button
11. Button b = new Button("Click Me!!");
12.
13. // setting button position on screen
14. [Link](30,100,80,30);
15.
16. // adding button into frame
17. add(b);
18.
19. // frame size 300 width and 300 height
20. setSize(300,300);
21.
22. // setting the title of Frame
23. setTitle("This is our basic AWT example");
24.
25. // no layout manager
26. setLayout(null);
27.
28. // now frame will be visible, by default it is not visible
29. setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[]) {
34.
35. // creating instance of Frame class
36. AWTExample1 f = new AWTExample1();
37.
38. }
39.
40. }
download this example
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above
example that sets the position of the awt button.
Output:
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.
[Link]
1. // importing Java AWT class
2. import [Link].*;
3.
4. // class AWTExample2 directly creates instance of Frame class
5. class AWTExample2 {
6.
7. // initializing using constructor
8. AWTExample2() {
9.
10. // creating a Frame
11. Frame f = new Frame();
12.
13. // creating a Label
14. Label l = new Label("Employee id:");
15.
16. // creating a Button
17. Button b = new Button("Submit");
18.
19. // creating a TextField
20. TextField t = new TextField();
21.
22. // setting position of above components in the frame
23. [Link](20, 80, 80, 30);
24. [Link](20, 100, 80, 30);
25. [Link](100, 100, 80, 30);
26.
27. // adding components into frame
28. [Link](b);
29. [Link](l);
30. [Link](t);
31.
32. // frame size 300 width and 300 height
33. [Link](400,300);
34.
35. // setting the title of frame
36. [Link]("Employee info");
37.
38. // no layout
39. [Link](null);
40.
41. // setting visibility of frame
42. [Link](true);
43. }
44.
45. // main method
46. public static void main(String args[]) {
47.
48. // creating instance of Frame class
49. AWTExample2 awt_obj = new AWTExample2();
50.
51. }
52.
53. }
download this example
Output:
Java's Abstract Window Toolkit (AWT) provides a set of classes for creating graphical user
interfaces and painting graphics.
Java AWT Classes
Java AWT Label
A Label is a non-interactive text display element in Java AWT. It is used to present a single
line of read-only text in a GUI. Labels are often used to identify other GUI components or
provide instructions to the user. They can be aligned using constants like [Link],
[Link], and [Link].
Java AWT Button
A Button is a GUI component that triggers an action event when clicked. It is used to perform
a specific action, such as submitting a form or initiating a process. Buttons can display text or
an image, and they support adding event listeners to handle user interactions.
Java AWT TextField
A TextField is a single-line text input component in Java AWT. It allows users to enter and
edit text. TextField supports setting the initial text, getting the text input, and adding event
listeners for actions such as pressing the Enter key.
Java AWT Checkbox
A Checkbox is a GUI component that can be either checked or unchecked. It is used for
options where the user can select or deselect an item independently. Checkboxes can be
grouped using CheckboxGroup to allow only one selection from the group.
Java AWT CheckboxGroup
A CheckboxGroup is used to group a set of checkboxes where only one checkbox can be
selected at a time. This is useful for presenting a set of mutually exclusive options, similar to
radio buttons. Only one checkbox in the group can be checked at any given time.
Java AWT Choice
A Choice is a drop-down list that allows users to select one item from a list of predefined
options. It is useful for compactly presenting multiple choices in a GUI. Choice components
are easy to integrate and manage, providing a simple way to select from a list.
Java AWT List
A List component displays a list of items, allowing the user to select one or more items from
the list. It can be configured to support single or multiple selections. List is useful for
presenting multiple selectable options in a scrollable area.
Java AWT Canvas
A Canvas is a blank rectangular area where custom graphics can be drawn. It is a subclass of
Component and provides a surface for drawing shapes, images, or handling custom
rendering. Developers override the paint method to define custom drawing logic.
AWT Scrollbar
A Scrollbar is a component that enables users to select a value from a range by sliding a knob
along a track. It can be oriented horizontally or vertically and is useful for navigating through
large content areas or adjusting values dynamically.
Java AWT MenuItem & Menu
MenuItem and Menu are used to create hierarchical drop-down menus in a GUI. MenuItem
represents individual menu options, while Menu groups related items together. They are
added to a MenuBar to provide structured navigation and actions in an application.
Java AWT PopupMenu
A PopupMenu is a context menu that appears upon user interaction, typically via a right-
click. It provides a list of actions relevant to the interaction's context. PopupMenu is useful
for offering context-specific options without cluttering the main interface.
Java AWT Panel
A Panel is a container that groups other components together. It is used to organize and
manage the layout of multiple GUI elements. Panels can contain other panels, allowing for
complex nested layouts and better organization of interface components.
Java AWT Toolkit
The Toolkit class is an abstract superclass that provides a platform-independent interface to
interact with various resources and capabilities of the AWT. It includes methods to get screen
resolution, image handling, and other system-level services that support GUI operations.
Event Handling in Java AWT
Event handling is a fundamental aspect of building interactive applications in Java, especially
when using the Abstract Window Toolkit (AWT) for creating graphical user interfaces
(GUIs). In Java AWT, events are generated by user interactions such as mouse clicks, key
presses, and window actions. To respond to these events, Java provides a robust event-
handling mechanism that includes various listener interfaces and event classes.
Listeners are objects that "listen" for specific types of events and handle them when they
occur. Each listener interface in Java AWT defines one or more methods that correspond to
specific events. By implementing these interfaces and overriding their methods, developers
can define custom behavior for different user actions. Here are some of the key event
handling components in Java AWT:
Java ActionListener
ActionListener is used to handle action events, such as button clicks. When an action occurs,
the actionPerformed(ActionEvent e) method is invoked.
Java MouseListener
MouseListener handles mouse events including clicks, presses, releases, entries, and exits. It
provides methods like mouseClicked(MouseEvent e), mousePressed(MouseEvent e),
mouseReleased(MouseEvent e), mouseEntered(MouseEvent e), and
mouseExited(MouseEvent e).
Java MouseMotionListener
MouseMotionListener handles mouse motion events, such as mouse movements and
dragging. It includes methods mouseMoved(MouseEvent e) and mouseDragged(MouseEvent
e).
Java ItemListener
ItemListener handles item events for components like checkboxes and choice lists. It contains
the itemStateChanged(ItemEvent e) method, which is called when an item's state changes.
Java KeyListener
KeyListener handles keyboard events. It provides methods keyTyped(KeyEvent e),
keyPressed(KeyEvent e), and keyReleased(KeyEvent e) to respond to key inputs.
Java WindowListener
WindowListener handles window events such as opening, closing, activation, deactivation,
and others. It includes methods like windowOpened(WindowEvent e),
windowClosing(WindowEvent e), windowClosed(WindowEvent e),
windowIconified(WindowEvent e), windowDeiconified(WindowEvent e),
windowActivated(WindowEvent e), and windowDeactivated(WindowEvent e).
Close AWT Window
To handle closing an AWT window, you typically implement the
windowClosing(WindowEvent e) method from the WindowListener interface, where you can
call [Link](0) to terminate the application.
Advantages of AWT in Java
1. Platform Independence: AWT provides a platform-independent way to create GUIs. The
same code can run on different operating systems without modification.
2. Integration with Native System: AWT components are heavyweight, meaning they use the
host operating system's native GUI components. It allows for better integration with the
system's look and feel.
3. Ease of Use: AWT provides a straightforward and relatively simple API for creating basic GUI
applications. It is a good starting point for beginners in Java GUI development.
4. Event Handling: AWT includes a powerful event handling model that allows developers to
capture and respond to various user interactions like mouse clicks, key presses, and window
events.
5. Basic Layout Managers: AWT offers basic layout managers such as FlowLayout,
BorderLayout, and GridLayout, which help in arranging components in a container without
needing explicit positioning.
6. Lightweight Components: With the introduction of Swing (which extends AWT), developers
can use lightweight components that do not rely on native peers, offering more flexibility
and customization.
7. Robustness: Being part of the Java standard library, AWT is well-tested and robust, ensuring
stability and reliability in applications.
8. Backward Compatibility: AWT has been around since Java 1.0, making it compatible with
older Java applications and ensuring that legacy applications can still be maintained and run.
9. Rich Set of Components: AWT provides a wide range of components such as buttons, labels,
text fields, checkboxes, lists, menus, and dialogs, enabling the creation of diverse user
interfaces.
10. Custom Drawing Capabilities: AWT includes the Canvas component, which allows for
custom drawing and rendering, providing the flexibility to create complex graphics and
custom GUI elements.
Disadvantages of AWT in Java
1. Limited Customization: AWT components are heavyweight, meaning they rely on the native
GUI components of the host operating system. This can limit the level of customization and
flexibility compared to lightweight components provided by Swing.
2. Platform Dependence Issues: Although AWT aims for platform independence, the reliance
on native components can lead to inconsistent behavior and appearance across different
platforms.
3. Basic Look and Feel: AWT components are basic and lack the advanced look and feel
available in more modern GUI toolkits like Swing or JavaFX. They often appear outdated and
less visually appealing.
4. Limited Components: AWT provides a relatively small set of GUI components compared to
Swing and JavaFX. It can make it challenging to create complex and feature-rich user
interfaces.
5. Threading Issues: AWT is not inherently thread-safe, and developers must be careful to
perform GUI updates on the Event Dispatch Thread (EDT) to avoid concurrency issues.
6. Performance Overhead: The use of heavyweight components can introduce performance
overhead, especially when rendering complex interfaces or handling extensive user
interactions.
7. Lack of Advanced Features: AWT lacks many of the advanced features found in Swing and
JavaFX, such as better event handling, data binding, and more sophisticated layout
management.
8. Obsolescence: With the advent of Swing and JavaFX, AWT is obsolete for modern
application development. Swing and JavaFX provide more features, better performance, and
more modern UI capabilities.
9. Limited Layout Managers: The layout managers provided by AWT (FlowLayout,
BorderLayout, GridLayout) are relatively simple and can be restrictive for designing complex
interfaces.
Labels
The easiest control to use is a label. A label contains a string and is an object of type
Label. Labels are passive controls that do not support any interaction with the user.
Creating Label : Label l = new Label(String);
Label Constructors:
1. Label() throws HeadlessException: It creates a blank label.
2. Label(String str) throws HeadlessException: It creates a label that contains the
string specified by str.
3. Label(String str, int how): It creates a label that contains the string specified by str
using the alignment specified by how. The value of how must be one of these three
constants: [Link], [Link], [Link].
Label Methods:
1. void setText(String str): It is used to set or change the text in a label by using the
setText() method. Here, str specifies the new label.
2. String getText(): It is used to obtain the current label by calling getText() method.
Here, the current label is returned.
3. void setAlignment(int how): It is used to set the alignment of the string within the
label by calling setAlignment() method. Here, how is one of the alignment constants?
4. int getAlignment(): It is used to obtain the current alignment, getAlignment() is
called.
AWT Button Control in Java
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. A button is basically a control
component with a label that generates an event when pushed. The Button class is used to
create a labeled button that has platform independent implementation. The application result
in some action when the button is pushed.
When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives the
all the events, then it passes an action event by calling its own method processActionEvent.
This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.
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:
AWR Canvas
Control in java
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. BufferStrategy getBufferStrategy(): It is used to return the BufferStrategy used by
this component.
Example to understand AWT Canvas Control in Java:
AWT Checkbox
Control in java
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, CheckboxGroup cbGroup) throws
HeadlessException or Checkbox(String str, CheckboxGroup cbGroup, 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. boolean getState(): 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:
CheckboxGroup: Radio Buttons
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 :
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
CheckboxGroup Methods
1. Checkbox getSelectedCheckbox(): You can determine which checkbox in a group
is currently selected by calling getSelectedCheckbox().
2. void setSelectedCheckbox(Checkbox which): You can set a checkbox by calling
setSelectedCheckbox(). Here, is the checkbox that you simply want to be selected.
The previously selected checkbox is going to be turned off.
Example to understand AWT CheckboxGroup Control in Java:
AWT Choice
Control in Java
This component will display a group of times as a drop-down menu from which a
user can select only one item. The choice component is used to create a pop-up list
of items from which the user may choose. Therefore, Choice control is a form of a
menu. When it is inactive, a Choice component takes up only enough space to show
the currently selected item. When the user clicks on a Choice component, the whole
list of choices pops up, and a new selection can be made.
Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
1. void add(String name): To add a selection to the list, use add(). Here, the name is
the name of the item being added.
2. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
6. void select(String name): It is used to set the currently selected item with a string
that will match a name in the list.
7. String getItem(int index): It is used to obtain the name associated with the item at
the given index. Here, the index specifies the index of the desired items.
Example to understand AWT Choice Control in Java:
AWT List Control in Java:
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, boolean multipleSelect) throws HeadlessException: If
multipleSelect is true, then the user may select two or more items at a time. If it’s
false, then just one item could also be selected.
Method of Lists
1. void add(String name): To add a selection to the list, use add(). Here, the name is
the name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the items
at the index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item. If more than one item is selected, or if no
selection has been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item. The first item is at index 0. If more than one item is selected, or if
no selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array
containing the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
9. String getItem(int index): It is used to obtain the name associated with the item at
the given index. Here, the index specifies the index of the desired items.
Example to understand AWT List Control in Java:
Java AWT TextField
The TextField class implements a single-line
text-entry area. Text fields allow the
user to enter strings and to edit the text
using the arrow keys, cut and paste keys,
and mouse
selections.
TextField is a subclass of TextComponent.
TextField defines the following
constructors:
The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.
When we enter a key in the text field (like
key pressed, key released or key typed), the
event is sent to TextField. Then the
KeyEvent is passed to the registered
KeyListener. It can also be done using
ActionEvent; if the ActionEvent is enabled
on the text field, then the ActionEvent may
be fired by pressing return key. The event is
handled by the ActionListener interface.
AWT Scrollbar Class