0% found this document useful (0 votes)
10 views

Awt-Swing-Java

This document provides study material on building Graphical User Interfaces (GUIs) in Java using AWT and Swing, covering event handling mechanisms. It discusses the differences between AWT and Swing, including component types, layout managers, and event delegation models. Additionally, it includes example code for creating simple applications and handling events using various methods such as anonymous inner classes and lambda expressions.

Uploaded by

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

Awt-Swing-Java

This document provides study material on building Graphical User Interfaces (GUIs) in Java using AWT and Swing, covering event handling mechanisms. It discusses the differences between AWT and Swing, including component types, layout managers, and event delegation models. Additionally, it includes example code for creating simple applications and handling events using various methods such as anonymous inner classes and lambda expressions.

Uploaded by

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

Java GUI and Event Handling Study Material

Study material on building Graphical User Interfaces (GUIs) in Java using AWT and
Swing, and how to handle events in these applications.

Topic 1: Abstract Window Toolkit (AWT): Introduction & AWT


Controls
●​ Introduction to AWT:
○​ AWT is Java's original windowing toolkit for creating Graphical User Interfaces
(GUIs).
○​ It provides a set of classes for creating windows, buttons, text fields, and
other GUI elements.
○​ AWT is "heavyweight," meaning it relies on the native operating system's GUI
components. This can lead to platform-dependent look and feel and behavior.
○​ It is part of the java.awt package.
●​ Components and Containers:
○​ Component: The base class for all AWT GUI elements (buttons, labels, text
fields, etc.). Components are things you see and interact with on the screen.
○​ Container: A type of Component that can hold other Components and
Containers. Examples include Frame, Panel, Dialog. Containers are used to
group and arrange components.
●​ Basic AWT Program Structure:
○​ Typically involves creating a Frame (a top-level window).
○​ Adding components to the frame or a panel within the frame.
○​ Setting a layout manager to arrange components.
○​ Making the frame visible.
●​ Common AWT Controls (Components):
○​ Label: Displays read-only text.
○​ Button: A clickable button.
○​ TextField: Allows single-line text input.
○​ TextArea: Allows multi-line text input.
○​ Checkbox: A two-state checkbox.
○​ CheckboxGroup: Used to group Checkboxes so that only one can be selected
at a time (like radio buttons).
○​ Choice: A dropdown list of items.
○​ List: A scrollable list of text items.
○​ Scrollbar: A scrollbar.
○​ Canvas: A blank drawing area.
○​ Panel: A simple container used to group components.
○​ Frame: A top-level window with a title bar, borders, and buttons (minimize,
maximize, close).
○​ Dialog: A pop-up window, typically used for short interactions.
●​ Example Code (Simple AWT Frame with a Button):

import java.awt.*;​

public class SimpleAWTExample extends Frame {​
public SimpleAWTExample() {​
// Set the title of the frame​
setTitle("My AWT Window");​

// Create a button​
Button button = new Button("Click Me");​

// Add the button to the frame (using default FlowLayout)​
add(button);​

// Set the size of the frame​
setSize(300, 200);​

// Make the frame visible​
setVisible(true);​

// Handle window closing (using an anonymous inner class for a WindowListener)​
addWindowListener(new java.awt.event.WindowAdapter() {​
public void windowClosing(java.awt.event.WindowEvent windowEvent) {​
System.exit(0);​
}​
});​
}​

public static void main(String[] args) {​
new SimpleAWTExample();​
}​
}​
●​ Limitations of AWT:
○​ Heavyweight components lead to platform dependency.
○​ Limited set of components compared to Swing.
○​ More complex event handling model initially (though the delegation model
improved this).

Topic 2: Java Swing


●​ Introduction to Swing:
○​ Swing is a more comprehensive and flexible GUI toolkit that was introduced as
part of the Java Foundation Classes (JFC).
○​ It is built on top of AWT but uses "lightweight" components.
○​ Lightweight Components: Swing components are largely drawn by Java
itself, not by the native operating system. This results in a more consistent
look and feel across different platforms.
○​ Swing provides a richer set of components and features than AWT.
○​ It is part of the javax.swing package.
●​ Swing Components (Starting with 'J'):
○​ Swing components are similar in concept to AWT components but typically
have "J" at the beginning of their class names. They offer more features and
customization options.
○​ JLabel: Displays text and/or images.
○​ ImageIcon: Represents an icon, often used with JLabel or JButton.
○​ JButton: A clickable button with more features than AWT's Button.
○​ JToggleButton: A button that can be in one of two states (selected or not
selected).
○​ JCheckBox: A checkbox that can be selected or deselected.
○​ JRadioButton: A radio button, typically used in a ButtonGroup for mutual
exclusion.
○​ JTextField: Allows single-line text input.
○​ JTextArea: Allows multi-line text input.
○​ JPasswordField: A text field specifically for password input (characters are
hidden).
○​ JList: Displays a list of items.
○​ JComboBox: A dropdown list (combo box).
●​ Swing Containers:
○​ Swing has its own set of containers that inherit from AWT containers but
provide more Swing-specific capabilities.
○​ JFrame: A top-level window (Swing equivalent of AWT Frame). It has a
ContentPane where you add components.
○​ JPanel: A general-purpose lightweight container used to group components
(Swing equivalent of AWT Panel).
○​ JDialog: A pop-up dialog window.
○​ JApplet: A base class for Swing applets (less relevant now with the decline of
browser applets).
○​ Content Pane: A special container within top-level Swing containers (JFrame,
JDialog, JApplet) where you should add your GUI components. You access it
using getContentPane().
●​ Layout Managers:
○​ Layout managers are used to arrange components within a container. They
control the size and position of components.
○​ Both AWT and Swing use layout managers.
○​ Common Layout Managers:
■​ FlowLayout: Arranges components in a row, wrapping to the next row
when necessary (default for Panel and JPanel).
■​ BorderLayout: Arranges components in five regions: North, South, East,
West, and Center (default for Frame, JFrame, Dialog, JDialog).
■​ GridLayout: Arranges components in a grid of rows and columns.
■​ CardLayout: Manages components as a stack of cards, only one of which
is visible at a time.
■​ GridBagLayout: A complex and flexible layout manager that aligns
components based on a grid of cells.
■​ BoxLayout: Arranges components in a single row or column.
■​ SpringLayout: A flexible layout manager for complex layouts.
○​ You set the layout manager for a container using the setLayout() method.
●​ Swing vs Abstract Window Toolkit:
○​ Components: Swing components are lightweight (drawn by Java), AWT
components are heavyweight (rely on native OS).
○​ Look and Feel: Swing has a pluggable look and feel, allowing you to change
the appearance of the application (e.g., Metal, Nimbus, GTK+, Windows).
AWT's look and feel is determined by the native OS.
○​ Functionality: Swing provides a much richer set of components and
advanced features (like tooltips, borders, scroll panes, tables, trees).
○​ MVC Architecture: Swing components follow the Model-View-Controller
(MVC) design pattern, separating data (Model), presentation (View), and user
interaction (Controller). This makes Swing components more flexible and
customizable. AWT components are simpler and often combine these roles.
○​ Usage: Swing is the preferred and recommended toolkit for building modern
Java GUI applications. AWT is primarily used for backward compatibility or in
specific scenarios where interaction with the native OS is crucial.
●​ Example Code (Simple Swing JFrame with a Button):

import javax.swing.*;​
import java.awt.*;​
import java.awt.event.ActionEvent;​
import java.awt.event.ActionListener;​

public class SimpleSwingExample extends JFrame implements ActionListener {​

private JButton button;​
private JLabel label;​

public SimpleSwingExample() {​
// Set the title of the frame​
setTitle("My Swing Window");​

// Set the default close operation (exit the application when closed)​
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);​

// Set the layout manager for the frame's content pane​
setLayout(new FlowLayout());​

// Create a label​
label = new JLabel("Hello, Swing!");​
add(label);​

// Create a button​
button = new JButton("Click Me");​
// Add an ActionListener to the button (for event handling)​
button.addActionListener(this);​
add(button);​

// Set the size of the frame​
setSize(300, 200);​

// Make the frame visible​
setVisible(true);​
}​

@Override​
public void actionPerformed(ActionEvent e) {​
// This method is called when the button is clicked​
if (e.getSource() == button) {​
label.setText("Button Clicked!");​
}​
}​

public static void main(String[] args) {​
// Run the GUI creation on the Event Dispatch Thread (EDT)​
SwingUtilities.invokeLater(new Runnable() {​
public void run() {​
new SimpleSwingExample();​
}​
});​
}​
}​

Topic 3: Event Handling


●​ What is Event Handling?
○​ Event handling is the mechanism by which a program responds to user
actions (like clicking a button, typing text, moving the mouse) or other events
(like a timer firing).
○​ In GUI applications, it's how the application becomes interactive.
●​ The Event Delegation Model:
○​ This is the standard model for event handling in Java (used by both AWT and
Swing).
○​ It involves three main parts:
1.​ Event Source: The object that generates the event (e.g., a button, a text
field, a window).
2.​ Event: An object that encapsulates information about the event that
occurred (e.g., ActionEvent, MouseEvent, KeyEvent).
3.​ Event Listener: An object that is interested in being notified when a
specific type of event occurs. It implements a specific listener interface
(e.g., ActionListener, MouseListener, KeyListener).
●​ How it Works:
○​ An Event Listener "registers" itself with an Event Source.
○​ When an event occurs at the Event Source, the source creates an Event
object.
○​ The Event Source then "delegates" the handling of the event by calling the
appropriate method on all registered Event Listeners.
●​ Event Sources:
○​ Objects that can generate events.
○​ Examples: JButton, JTextField, JSlider, JFrame, etc.
○​ Event sources have methods for registering and unregistering listeners (e.g.,
addActionListener(), addMouseListener()).
●​ Event Listeners:
○​ Objects that implement specific listener interfaces.
○​ Listener interfaces define methods that the Event Source will call when an
event occurs.
○​ Examples of Listener Interfaces:
■​ ActionListener: For button clicks, menu selections, text field actions
(actionPerformed() method).
■​ MouseListener: For mouse button events (clicks, presses, releases,
entering/exiting a component - mouseClicked(), mousePressed(), etc.).
■​ MouseMotionListener: For mouse movement events (dragging, moving -
mouseDragged(), mouseMoved() methods).
■​ KeyListener: For keyboard events (keyPressed(), keyReleased(),
keyTyped() methods).
■​ WindowListener: For window events (opening, closing, minimizing,
maximizing - windowOpened(), windowClosing(), etc.).
■​ ItemListener: For selecting/deselecting items in components like
checkboxes or combo boxes (itemStateChanged() method).
■​ DocumentListener: For changes in a text component's document
(insertUpdate(), removeUpdate(), changedUpdate() methods).
●​ Event Classes:
○​ Objects that represent specific events. They contain information about the
event, such as the source of the event, the time it occurred, and specific
details relevant to the event type (e.g., mouse coordinates for a MouseEvent,
the command string for an ActionEvent).
○​ Event classes are subclasses of java.util.EventObject.
○​ Examples: ActionEvent, MouseEvent, KeyEvent, WindowEvent, ItemEvent,
DocumentEvent.
●​ Interfaces (Listener Interfaces):
○​ Define the methods that an event listener must implement to handle a specific
type of event.
●​ Implementing Event Handling (Common Approaches):
1.​ Implement the Listener Interface directly in your class: (See the
SimpleSwingExample above where the JFrame implements ActionListener).
2.​ Use a separate class that implements the listener interface: Create a
dedicated class for handling events.
3.​ Use an anonymous inner class: Define and instantiate a listener class
directly within the method where you need it (useful for simple, one-off
listeners).
4.​ Use a lambda expression: (Java 8 and later) A concise way to implement
single-method interfaces (functional interfaces) like many listener interfaces.
●​ Example Code (Using an Anonymous Inner Class for a Button Click):

import javax.swing.*;​
import java.awt.*;​
import java.awt.event.ActionEvent;​
import java.awt.event.ActionListener;​

public class EventHandlingAnonymousExample extends JFrame {​

public EventHandlingAnonymousExample() {​
setTitle("Anonymous Listener");​
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);​
setLayout(new FlowLayout());​

JButton button = new JButton("Click Me");​
JLabel label = new JLabel("Not clicked yet");​

// Add an ActionListener using an anonymous inner class​
button.addActionListener(new ActionListener() {​
@Override​
public void actionPerformed(ActionEvent e) {​
label.setText("Button was clicked!");​
}​
});​

add(button);​
add(label);​

setSize(300, 150);​
setVisible(true);​
}​

public static void main(String[] args) {​
SwingUtilities.invokeLater(new Runnable() {​
public void run() {​
new EventHandlingAnonymousExample();​
}​
});​
}​
}​

●​ Example Code (Using a Lambda Expression for a Button Click - Java 8+):

import javax.swing.*;​
import java.awt.*;​
import java.awt.event.ActionEvent; // Still need ActionEvent class​

public class EventHandlingLambdaExample extends JFrame {​

public EventHandlingLambdaExample() {​
setTitle("Lambda Listener");​
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);​
setLayout(new FlowLayout());​

JButton button = new JButton("Click Me");​
JLabel label = new JLabel("Not clicked yet");​

// Add an ActionListener using a lambda expression​
button.addActionListener(e -> label.setText("Button was clicked!"));​

add(button);​
add(label);​

setSize(300, 150);​
setVisible(true);​
}​

public static void main(String[] args) {​
SwingUtilities.invokeLater(() -> new EventHandlingLambdaExample());​
}​
}​

●​ Adapter Classes:
○​ For listener interfaces with multiple methods (like MouseListener or
WindowListener), Java provides "adapter" classes (e.g., MouseAdapter,
WindowAdapter).
○​ Adapter classes provide empty default implementations for all methods in the
corresponding listener interface.
○​ You can extend an adapter class and override only the methods you are
interested in, avoiding the need to implement all methods of the interface.
●​ Example Code (Using WindowAdapter to handle closing):

import javax.swing.*;​
import java.awt.*;​
import java.awt.event.WindowAdapter;​
import java.awt.event.WindowEvent;​

public class WindowAdapterExample extends JFrame {​

public WindowAdapterExample() {​
setTitle("Window Adapter");​
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Don't exit
automatically​
setSize(300, 150);​

// Add a WindowListener using a WindowAdapter​
addWindowListener(new WindowAdapter() {​
@Override​
public void windowClosing(WindowEvent e) {​
// This method is called when the user clicks the close button​
JOptionPane.showMessageDialog(null, "Window is closing!");​
System.exit(0); // Manually exit the application​
}​
});​

setVisible(true);​
}​

public static void main(String[] args) {​
SwingUtilities.invokeLater(() -> new WindowAdapterExample());​
}​
}​

●​ The Event Dispatch Thread (EDT):


○​ GUI events (like button clicks) are processed on a special single thread called
the Event Dispatch Thread (EDT).
○​ It is crucial to perform all GUI-related operations (creating and updating
components, handling events) on the EDT to avoid thread-safety issues.
○​ SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() are used to run
code on the EDT. You've seen invokeLater in the Swing examples – this is the
standard way to start a Swing application.

You might also like