Java AWT (Abstract Window
Toolkit)
From Basic to Advanced Concepts
Comprehensive 50-Slide Presentation
Table of Contents
• 1. Introduction to Java AWT (Slides 1-5)
• 2. AWT Architecture and Hierarchy (Slides 6-10)
• 3. Basic AWT Components (Slides 11-20)
• 4. Advanced Components and Controls (Slides 21-25)
• 5. Layout Managers (Slides 26-35)
• 6. Event Handling in AWT (Slides 36-40)
• 7. Graphics and Custom Painting (Slides 41-45)
• 8. Advanced Topics: Applets, Menus, Dialogs (Slides 46-50)
What is Java AWT?
• • Abstract Window Toolkit - Java's original GUI framework
• • Part of Java Foundation Classes (JFC) since Java 1.0
• • Platform-dependent windowing and user interface toolkit
• • Uses native OS components for rendering (heavyweight components)
• • Foundation for Swing and JavaFX frameworks
• • Provides basic GUI components like buttons, labels, text fields
• • Still widely used in enterprise applications and embedded systems
AWT Features and Characteristics
• • Platform Dependent: Components look native to the OS
• • Heavyweight Components: Use OS resources directly
• • Limited Component Set: Basic GUI controls available
• • Event-Driven Architecture: Based on listener pattern
• • Layout Managers: Automatic component positioning
• • Graphics Support: 2D drawing and painting capabilities
• • Thread Safety: GUI updates must occur on Event Dispatch Thread
• • Cross-platform Compatibility: Write once, run anywhere
AWT vs Swing vs JavaFX
• AWT (1995):
– - Heavyweight, platform-dependent, limited components
• Swing (1997):
– - Lightweight, platform-independent, rich component set
– - Built on top of AWT foundation
• JavaFX (2008):
– - Modern UI toolkit, rich graphics, CSS styling
– - Multimedia support, 3D graphics, animation
• Why Learn AWT?
– - Understanding of GUI fundamentals
– - Legacy application maintenance
– - Foundation for Swing development
AWT Architecture Overview
• • Component-Based Architecture
– - Everything is a Component or Container
• • Delegation Event Model
– - Event sources, listeners, and event objects
• • Layout Management System
– - Automatic component positioning and sizing
• • Graphics Context
– - Abstract Graphics class for drawing operations
• • Native Peer Architecture
– - Java components mapped to native OS widgets
AWT Class Hierarchy
• java.lang.Object
– └── java.awt.Component
– ├── java.awt.Button
– ├── java.awt.Label
– ├── java.awt.TextField
– ├── java.awt.TextArea
– ├── java.awt.Canvas
– └── java.awt.Container
– ├── java.awt.Panel
– └── java.awt.Window
– ├── java.awt.Frame
– └── java.awt.Dialog
Component vs Container
• Component Class:
– - Abstract base class for all AWT components
– - Defines common properties: size, position, visibility
– - Handles events and painting
• Container Class:
– - Extends Component
– - Can hold other components (composition)
– - Manages layout of child components
– - Examples: Panel, Frame, Dialog
• Key Difference:
– - Component: Individual UI element
– - Container: Groups and manages multiple components
Window, Frame, and Panel
• Window:
– - Top-level container, no borders or menu bar
– - Base class for Frame and Dialog
• Frame:
– - Window with title bar, border, and resizable corners
– - Can have menu bar attached
– - Main window for standalone applications
• Panel:
– - Lightweight container for grouping components
– - No title bar or border
– - Used for organizing UI layout
Creating Your First AWT Appl
Basic AWT application with Frame, Button, and even
import java.awt.*;
import java.awt.event.*;
public class FirstAWTApp extends Frame {
public FirstAWTApp() {
super("My First AWT Application");
setSize(300, 200);
setLayout(new FlowLayout());
Button btn = new Button("Click Me");
add(btn);
addWindowListener(new WindowAdapter
public void windowClosing(WindowEven
System.exit(0);
}
});
AWT Button Component
• • Most commonly used interactive component
• • Fires ActionEvent when clicked
• • Constructors:
– - Button() - Creates button with no label
– - Button(String label) - Creates button with label
• • Key Methods:
– - setLabel(String) - Sets button text
– - getLabel() - Gets button text
– - addActionListener() - Registers event listener
• • Usage: Triggering actions, form submission, navigation
Button Example
import java.awt.*;
import java.awt.event.*;
public class ButtonExample extends Frame implements
private Button btn1, btn2;
private Label label;
public ButtonExample() {
setTitle("Button Example");
setLayout(new FlowLayout());
btn1 = new Button("Click Me");
btn2 = new Button("Reset");
label = new Label("No button clicked yet");
btn1.addActionListener(this);
btn2.addActionListener(this);
add(btn1);
add(btn2);
add(label);
AWT Label Component
• • Displays read-only text
• • Non-interactive component for captions
• • Constructors:
– - Label() - Empty label
– - Label(String text) - Label with text
– - Label(String text, int alignment) - With alignment
• • Alignment Constants:
– - Label.LEFT, Label.CENTER, Label.RIGHT
• • Key Methods:
– - setText(String) - Changes label text
– - getText() - Gets current text
– - setAlignment(int) - Sets text alignment
AWT TextField Component
• • Single-line text input component
• • Supports text editing and selection
• • Constructors:
– - TextField() - Empty text field
– - TextField(int columns) - With specified width
– - TextField(String text) - With initial text
– - TextField(String text, int columns) - Text and width
• • Key Methods:
– - setText(String) / getText()
– - setEditable(boolean) - Enable/disable editing
– - setEchoChar(char) - For password fields
• • Events: ActionEvent (Enter key), TextEvent (text changes)
TextField Example
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements
private TextField nameField, emailField;
private Button submitBtn;
private Label resultLabel;
public TextFieldExample() {
setTitle("TextField Demo");
setLayout(new GridLayout(4, 2));
add(new Label("Name:"));
nameField = new TextField(20);
add(nameField);
add(new Label("Email:"));
emailField = new TextField(20);
add(emailField);
submitBtn = new Button("Submit");
AWT TextArea Component
• • Multi-line text input and display component
• • Supports text editing, scrolling, and selection
• • Constructors:
– - TextArea() - Empty text area
– - TextArea(int rows, int cols) - With dimensions
– - TextArea(String text) - With initial text
– - TextArea(String text, int rows, int cols, int scrollbars)
• • Scrollbar Constants:
– - SCROLLBARS_BOTH, SCROLLBARS_VERTICAL_ONLY
– - SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE
• • Methods: append(), insert(), replaceRange()
AWT Checkbox Component
• • Provides binary choice (checked/unchecked)
• • Can be used individually or in groups (radio buttons)
• • Constructors:
– - Checkbox() - Unchecked checkbox
– - Checkbox(String label) - With label
– - Checkbox(String label, boolean state) - With state
– - Checkbox(String label, CheckboxGroup group, boolean state)
• • Key Methods:
– - setState(boolean) / getState()
– - setLabel(String) / getLabel()
• • Events: ItemEvent when state changes
Checkbox Example
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample extends Frame implemen
private Checkbox cb1, cb2, cb3;
private Label resultLabel;
public CheckboxExample() {
setTitle("Checkbox Demo");
setLayout(new FlowLayout());
cb1 = new Checkbox("Java");
cb2 = new Checkbox("Python");
cb3 = new Checkbox("C++");
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
resultLabel = new Label("Select your favorite langua
Radio Buttons (CheckboxGroup)
• • Mutually exclusive checkboxes
• • Only one can be selected at a time
• • Uses CheckboxGroup class
• • Implementation:
– - Create CheckboxGroup object
– - Pass group to Checkbox constructor
– - All checkboxes in same group are mutually exclusive
• • Methods:
– - setSelectedCheckbox(Checkbox) - Select programmatically
– - getSelectedCheckbox() - Get current selection
• • Common use: Multiple choice questions, preferences
AWT Choice Component
• • Dropdown list for single selection
• • Space-efficient for multiple options
• • Key Methods:
– - add(String item) - Add item to list
– - insert(String item, int index) - Insert at position
– - remove(String item) - Remove item
– - select(int index) - Select item programmatically
– - getSelectedItem() - Get selected text
– - getSelectedIndex() - Get selected index
• • Events: ItemEvent when selection changes
• • Usage: Country selection, categories, options
Choice Example
import java.awt.*;
import java.awt.event.*;
public class ChoiceExample extends Frame implements
private Choice countryChoice;
private Label resultLabel;
public ChoiceExample() {
setTitle("Choice Demo");
setLayout(new FlowLayout());
add(new Label("Select Country:"));
countryChoice = new Choice();
countryChoice.add("USA");
countryChoice.add("Canada");
countryChoice.add("UK");
countryChoice.add("India");
countryChoice.add("Japan");
countryChoice.addItemListener(this);
AWT List Component
• • Scrollable list of text items
• • Supports single or multiple selection
• • Constructors:
– - List() - Single selection list
– - List(int rows) - With visible rows
– - List(int rows, boolean multipleMode) - Multi-selection
• • Key Methods:
– - add(String item) - Add item
– - getSelectedItem() / getSelectedItems()
– - getSelectedIndex() / getSelectedIndexes()
– - isIndexSelected(int index)
• • Events: ActionEvent (double-click), ItemEvent (selection)
AWT Canvas Component
• • Blank rectangular drawing area
• • Used for custom graphics and animations
• • Must be subclassed for useful functionality
• • Override paint(Graphics g) method for drawing
• • Key Features:
– - Custom drawing and painting
– - Game development
– - Data visualization
– - Image display and manipulation
• • Methods:
– - paint(Graphics g) - Override for custom drawing
– - repaint() - Request redraw
– - setSize() - Set canvas dimensions
Canvas Example
import java.awt.*;
import java.awt.event.*;
class DrawingCanvas extends Canvas {
public void paint(Graphics g) {
// Set background color
setBackground(Color.WHITE);
// Draw shapes
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
g.setColor(Color.BLUE);
g.fillRect(200, 50, 100, 100);
g.setColor(Color.GREEN);
int[] xPoints = {350, 300, 400};
int[] yPoints = {50, 150, 150};
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(Color.BLACK);
AWT Scrollbar Component
• • Provides scrolling capability
• • Can be horizontal or vertical
• • Constructors:
– - Scrollbar() - Vertical scrollbar
– - Scrollbar(int orientation) - HORIZONTAL/VERTICAL
– - Scrollbar(int orientation, int value, int visible, int min, int max)
• • Key Methods:
– - setValue(int) / getValue()
– - setMinimum(int) / setMaximum(int)
– - setVisibleAmount(int) - Thumb size
• • Events: AdjustmentEvent when scrolled
• • Usage: Large content navigation, sliders
Introduction to Layout Managers
• • Automatic positioning and sizing of components
• • Platform-independent UI layout
• • Container's responsibility to manage child components
• • Types of Layout Managers:
– - FlowLayout - Sequential arrangement
– - BorderLayout - Five regions
– - GridLayout - Tabular arrangement
– - CardLayout - Stacked components
– - GridBagLayout - Complex flexible layout
• • Benefits:
– - Responsive design
– - Consistent appearance across platforms
FlowLayout Manager
• • Default layout for Panel and Applet
• • Arranges components in rows, left to right
• • Wraps to next row when space runs out
• • Constructors:
– - FlowLayout() - Default center alignment
– - FlowLayout(int align) - Specified alignment
– - FlowLayout(int align, int hgap, int vgap) - With gaps
• • Alignment Constants:
– - FlowLayout.LEFT, CENTER, RIGHT, LEADING, TRAILING
• • Best for: Toolbars, button groups, simple forms
FlowLayout Example
Components flow left-to-right, wrapping to new row
import java.awt.*;
public class FlowLayoutExample extends Frame {
public FlowLayoutExample() {
setTitle("FlowLayout Demo");
// Set FlowLayout with center alignment and g
setLayout(new FlowLayout(FlowLayout.CENTE
// Add multiple buttons
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button("Button 3"));
add(new Button("Very Long Button 4"));
add(new Button("Button 5"));
add(new Button("Button 6"));
add(new Button("Short"));
BorderLayout Manager
• • Default layout for Frame, Dialog, and Window
• • Divides container into five regions:
– - NORTH (top), SOUTH (bottom)
– - EAST (right), WEST (left)
– - CENTER (middle)
• • Each region can hold only one component
• • CENTER region gets remaining space
• • Constructors:
– - BorderLayout() - No gaps
– - BorderLayout(int hgap, int vgap) - With gaps
• • Usage: Application main windows, dialog layouts
BorderLayout Example
Five regions: NORTH, SOUTH, EAST, WEST, CEN
import java.awt.*;
public class BorderLayoutExample extends Frame
public BorderLayoutExample() {
setTitle("BorderLayout Demo");
// BorderLayout is default for Frame, but bein
setLayout(new BorderLayout(5, 5));
// Add components to different regions
add(new Button("NORTH"), BorderLayout.NO
add(new Button("SOUTH"), BorderLayout.SO
add(new Button("EAST"), BorderLayout.EAST
add(new Button("WEST"), BorderLayout.WES
add(new Button("CENTER"), BorderLayout.CE
setSize(400, 300);
GridLayout Manager
• • Arranges components in rectangular grid
• • All components have equal size
• • Fills grid left-to-right, top-to-bottom
• • Constructors:
– - GridLayout() - Single row, multiple columns
– - GridLayout(int rows, int cols) - Specified dimensions
– - GridLayout(int rows, int cols, int hgap, int vgap) - With gaps
• • Rules:
– - One of rows or cols can be zero (flexible)
– - If both specified, rows takes precedence
• • Best for: Calculators, button grids, uniform layouts
GridLayout Example - Calcu
import java.awt.*;
import java.awt.event.*;
public class CalculatorLayout extends Frame implements
private TextField display;
private String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
public CalculatorLayout() {
setTitle("Calculator Layout");
setLayout(new BorderLayout());
// Display at top
display = new TextField("0");
display.setEditable(false);
add(display, BorderLayout.NORTH);
CardLayout Manager
• • Shows one component at a time (like a deck of cards)
• • Useful for wizards, tabbed interfaces, multi-step forms
• • Components stacked on top of each other
• • Only top card is visible
• • Key Methods:
– - show(Container parent, String name) - Show named card
– - first(Container parent) - Show first card
– - last(Container parent) - Show last card
– - next(Container parent) - Show next card
– - previous(Container parent) - Show previous card
• • Must add components with string names
CardLayout Example
import java.awt.*;
import java.awt.event.*;
public class CardLayoutExample extends Frame implement
private CardLayout cardLayout;
private Panel cardPanel;
private Button prevBtn, nextBtn;
public CardLayoutExample() {
setTitle("CardLayout Demo");
setLayout(new BorderLayout());
// Create card layout and panel
cardLayout = new CardLayout();
cardPanel = new Panel(cardLayout);
// Create different cards
Panel card1 = new Panel();
card1.setBackground(Color.RED);
card1.add(new Label("Card 1 - Red"));
GridBagLayout Manager
• • Most flexible and complex layout manager
• • Components can span multiple rows/columns
• • Different sized components in same grid
• • Uses GridBagConstraints to specify positioning
• • Key GridBagConstraints fields:
– - gridx, gridy - Grid position
– - gridwidth, gridheight - Span multiple cells
– - fill - How component fills allocated space
– - anchor - Alignment within cell
– - weightx, weighty - Extra space distribution
– - insets - External padding
Introduction to Event Handling
• • Event-Driven Programming Model
• • Three key participants:
– - Event Source: Component that generates events
– - Event Object: Contains event information
– - Event Listener: Handles the event
• • Delegation Event Model (since JDK 1.1):
– - Events are delegated to registered listeners
– - Multiple listeners can handle same event
– - Loose coupling between source and handler
• • Event handling steps:
– 1. Implement listener interface
– 2. Register listener with source
– 3. Handle event in listener method
Event Classes and Listener Interfaces
• Common Event Types:
• • ActionEvent → ActionListener
– - Button clicks, menu selections, Enter key
• • MouseEvent → MouseListener, MouseMotionListener
– - Mouse clicks, press/release, enter/exit, move/drag
• • KeyEvent → KeyListener
– - Key press, release, typed
• • WindowEvent → WindowListener
– - Window open/close, minimize/maximize, focus
• • ItemEvent → ItemListener
– - Checkbox, Choice, List selection changes
• • TextEvent → TextListener
– - Text component content changes
ActionListener Example
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample extends Frame impleme
private Button btn1, btn2, btn3;
private TextField textField;
private int counter = 0;
public ActionListenerExample() {
setTitle("ActionListener Demo");
setLayout(new FlowLayout());
btn1 = new Button("Increment");
btn2 = new Button("Decrement");
btn3 = new Button("Reset");
textField = new TextField(10);
// Register this object as listener for all buttons
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
MouseListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame impleme
private Label statusLabel;
private int clickCount = 0;
public MouseListenerExample() {
setTitle("MouseListener Demo");
setLayout(new BorderLayout());
statusLabel = new Label("Click anywhere in the window
statusLabel.setAlignment(Label.CENTER);
add(statusLabel, BorderLayout.SOUTH);
// Register mouse listener on the frame
addMouseListener(this);
setSize(400, 300);
setVisible(true);
}
KeyListener Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements K
private TextArea textArea;
private Label statusLabel;
public KeyListenerExample() {
setTitle("KeyListener Demo");
setLayout(new BorderLayout());
textArea = new TextArea(10, 40);
textArea.addKeyListener(this);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 1
statusLabel = new Label("Type in the text area above");
statusLabel.setBackground(Color.LIGHT_GRAY);
add(textArea, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
Introduction to AWT Graphics
• • Graphics class provides drawing capabilities
• • Abstract class - cannot be instantiated directly
• • Obtained through:
– - paint(Graphics g) method parameter
– - getGraphics() method on components
• • Graphics Context contains:
– - Current drawing color
– - Current font
– - Clipping region
– - Coordinate system
• • Drawing Methods:
– - drawLine(), drawRect(), drawOval()
– - fillRect(), fillOval(), fillPolygon()
– - drawString(), drawImage()
Basic Drawing Methods
• Shape Drawing:
• • drawLine(int x1, int y1, int x2, int y2)
• • drawRect(int x, int y, int width, int height)
• • fillRect(int x, int y, int width, int height)
• • drawOval(int x, int y, int width, int height)
• • fillOval(int x, int y, int width, int height)
• Text Drawing:
• • drawString(String str, int x, int y)
• • setFont(Font font) - Set text font
• Color and Style:
• • setColor(Color c) - Set drawing color
• • Available colors: Color.RED, BLUE, GREEN, etc.
• • Custom colors: new Color(r, g, b)
Graphics Example - Custom C
import java.awt.*;
class GraphicsCanvas extends Canvas {
public void paint(Graphics g) {
// Set background
setBackground(Color.WHITE);
// Draw rectangles
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 80);
g.setColor(Color.BLACK);
g.drawRect(50, 50, 100, 80);
// Draw circles
g.setColor(Color.BLUE);
g.fillOval(200, 50, 100, 100);
g.setColor(Color.BLACK);
g.drawOval(200, 50, 100, 100);
// Draw lines
g.setColor(Color.GREEN);
Animation Example
import java.awt.*;
import java.awt.event.*;
class AnimationCanvas extends Canvas implements
private int ballX = 0, ballY = 100;
private int deltaX = 2, deltaY = 2;
private Thread animationThread;
public AnimationCanvas() {
setBackground(Color.WHITE);
animationThread = new Thread(this);
animationThread.start();
}
public void paint(Graphics g) {
// Clear background
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
// Draw bouncing ball
g.setColor(Color.RED);
Working with Images
• • Loading Images:
– - Toolkit.getDefaultToolkit().getImage(filename)
– - Image.getImage(URL) for web images
• • Drawing Images:
– - drawImage(Image img, int x, int y, ImageObserver observer)
– - drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
• • Image Observer:
– - Usually pass 'this' as ImageObserver
– - Handles asynchronous image loading
• • Common formats: GIF, JPEG, PNG
• • Use MediaTracker for multiple image loading
• • Double buffering for smooth animations
Introduction to Java Applets
• • Small Java programs that run in web browsers
• • Embedded in HTML pages using <applet> tag
• • Extends java.applet.Applet class
• • Security restrictions (sandbox model):
– - Cannot read/write local files
– - Limited network access
– - Cannot execute system commands
• • Applet Lifecycle Methods:
– - init() - Initialize applet
– - start() - Start execution
– - stop() - Pause execution
– - destroy() - Clean up resources
• • No main() method - lifecycle managed by browser
Basic Applet Example
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet.class" width="400" hei
</applet>
*/
public class SimpleApplet extends Applet {
private String message = "";
private int counter = 0;
public void init() {
// Initialize applet
setBackground(Color.LIGHT_GRAY);
setLayout(new FlowLayout());
Button btn = new Button("Click Me!");
add(btn);
btn.addActionListener(e -> {
AWT Menus
• • MenuBar: Container for menus (attached to Frame)
• • Menu: Drop-down menu containing menu items
• • MenuItem: Individual selectable menu option
• • CheckboxMenuItem: Menu item with checkbox
• • Menu Hierarchy:
– - Frame.setMenuBar(MenuBar)
– - MenuBar.add(Menu)
– - Menu.add(MenuItem)
• • Key Methods:
– - addSeparator() - Add menu separator line
– - setEnabled(boolean) - Enable/disable items
– - addActionListener() - Handle menu selections
• • Keyboard shortcuts supported
Complete Menu Exampl
import java.awt.*;
import java.awt.event.*;
public class MenuExample extends Frame implements A
private TextArea textArea;
private Label statusLabel;
public MenuExample() {
setTitle("Menu Demo");
setLayout(new BorderLayout());
// Create menu bar
MenuBar menuBar = new MenuBar();
// File menu
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");
Dialog Boxes and Summary
• Dialog Boxes:
• • Modal dialogs block interaction with parent window
• • FileDialog - File selection dialog
– - FileDialog(Frame parent, String title, int mode)
– - LOAD mode for opening, SAVE mode for saving
• • Custom Dialog classes extend Dialog
• • PopupMenu - Context menus triggered by right-click
• AWT Summary - Key Concepts:
• • Component hierarchy and containers
• • Layout managers for responsive UI
• • Event-driven programming with listeners
• • Custom graphics and painting
• • Platform-dependent but portable