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

JAVA_-_UNIT_4

The document provides an overview of AWT (Abstract Window Toolkit) in Java, detailing its role in creating graphical user interfaces (GUIs) and the various components it includes, such as container and non-container classes. It explains event handling, including the concepts of events, event sources, and listeners, along with examples of handling button and window events. Additionally, it covers the Graphics class for drawing shapes and text, as well as the creation of menus in AWT applications.

Uploaded by

SS GAMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA_-_UNIT_4

The document provides an overview of AWT (Abstract Window Toolkit) in Java, detailing its role in creating graphical user interfaces (GUIs) and the various components it includes, such as container and non-container classes. It explains event handling, including the concepts of events, event sources, and listeners, along with examples of handling button and window events. Additionally, it covers the Graphics class for drawing shapes and text, as well as the creation of menus in AWT applications.

Uploaded by

SS GAMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

🍵

JAVA - UNIT 4
1. AWT (Abstract Window Toolkit)

What is AWT?
AWT is a part of Java's java.awt package and is used to create Graphical User
Interfaces (GUIs) for Java applications.

It provides a set of classes for creating windows, buttons, text fields, and
other UI components.

CUI vs. GUI


1. CUI (Character User Interface):

Text-based interface where users interact with commands.

Example: Command Prompt.

2. GUI (Graphical User Interface):

Visual interface using windows, buttons, text boxes, etc.

Example: Modern applications like browsers or text editors.

AWT Classes
AWT components are divided into container classes and non-container classes.

1. Container Classes:
Containers are used to hold and organize other components (like buttons,
labels).

Examples:

Frame: Main window that can hold other components.

Panel: Sub-container used for organizing components inside a container.

2. Non-Container Classes:
Components that cannot contain other elements but provide specific
functionalities.

Examples:

Label : Displays a single line of text.

Button : Creates clickable buttons.

TextField : Allows the user to input text in a single line.

TextArea : Allows the user to input text in multiple lines.

JAVA - UNIT 4 1
Checkbox : A box that can be selected or deselected.

Choice : Dropdown menu.

List : A scrollable list of items.

Scrollbar : A scrollable bar for navigation.

AWT Frame
The Frame class is the top-level window in AWT used to display other components.

Common Methods of Frame :


1. setTitle(String title) : Sets the title of the frame.

2. setBackground(Color color) : Sets the background color.

3. setForeground(Color color) : Sets the text and component color.

4. setSize(int width, int height) : Sets the dimensions of the frame.

5. setVisible(boolean visible) : Makes the frame visible or invisible.

6. setLayout(LayoutManager layout) : Sets the layout of components inside the frame.

7. add(Component comp) : Adds a component to the frame.

Example:

import java.awt.*;

public class AWTFrameExample {


public static void main(String[] args) {
Frame frame = new Frame("My AWT Frame");

// Setting properties
frame.setSize(400, 300);
frame.setLayout(new FlowLayout());
frame.setBackground(Color.LIGHT_GRAY);

// Adding components
Button button = new Button("Click Me");
frame.add(button);

frame.setVisible(true); // Display the frame


}
}

AWT Panel
The Panel class is a simple container that groups components inside a
container like a Frame .

JAVA - UNIT 4 2
Panels are used to organize the layout within a frame.

Example:

import java.awt.*;

public class AWTPanelExample {


public static void main(String[] args) {
Frame frame = new Frame("AWT Panel Example");
Panel panel = new Panel();

// Adding components to the panel


panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));

// Adding panel to the frame


frame.add(panel);

frame.setSize(300, 200);
frame.setVisible(true);
}
}

AWT Layout Management


AWT provides layout managers to control the arrangement of components within
containers.

1. FlowLayout:

Arranges components in a left-to-right flow, wrapping to the next line as


needed.

Example:

frame.setLayout(new FlowLayout());

2. BorderLayout:

Divides the container into 5 regions: NORTH , SOUTH , EAST , WEST , CENTER .

Example:

frame.setLayout(new BorderLayout());

3. GridLayout:

Arranges components in a grid with equal-sized cells.

Example:

JAVA - UNIT 4 3
frame.setLayout(new GridLayout(2, 2)); // 2 rows, 2 co
lumns

4. CardLayout:

Allows multiple components to occupy the same space, showing one at a


time.

Example:

CardLayout layout = new CardLayout();


frame.setLayout(layout);

5. GridBagLayout:

Flexible layout manager that aligns components both vertically and


horizontally.

2. Event Handling in AWT

What is Event Handling?


Event handling in AWT refers to the mechanism that allows a program to
respond to user actions like button clicks, key presses, or mouse movements.

In AWT, events are generated by user interactions or system actions and are
processed using event listeners.

Key Concepts
1. Event:

An event represents a change in the state of an object, triggered by user


interaction or system activity.

Example: Clicking a button generates an ActionEvent.

2. Event Source:

The object (component) that generates an event.

Example: A Button or TextField .

3. Event Listener:

An object that listens to and processes events.

Example: A class that implements ActionListener to handle button click


events.

4. Event Object:

Encapsulates information about the event.

Example: ActionEvent , MouseEvent , KeyEvent .

JAVA - UNIT 4 4
Steps for Event Handling
1. Registering the Event Source:

Connect the component (e.g., Button ) with an event listener.

Example: button.addActionListener(listener);

2. Implementing the Listener Interface:

Write the logic to handle the event by implementing the appropriate


listener interface.

3. Overriding the Listener Method:

Define the action to be performed when the event occurs.

Event Classes and Listener Interfaces

Common Event Classes:


Event Class Description Common Source
ActionEvent Generated when a button is clicked. Button , MenuItem , TextField

MouseEvent Generated for mouse actions. Component

KeyEvent Generated for keyboard actions. Component

WindowEvent Generated for window actions. Window

ItemEvent Generated for item selection. Checkbox , Choice , List

Common Listener Interfaces:

Listener Interface Method to Implement Handles Event Class


ActionListener void actionPerformed(ActionEvent e) ActionEvent

MouseListener void mouseClicked(MouseEvent e) MouseEvent

KeyListener void keyPressed(KeyEvent e) KeyEvent

WindowListener void windowClosing(WindowEvent e) WindowEvent

Button Events: ActionEvent and ActionListener

Example of Handling Button Clicks:

import java.awt.*;
import java.awt.event.*;

public class ButtonEventExample extends Frame implements Acti


onListener {
Button button;

public ButtonEventExample() {
// Create a button and set its properties
button = new Button("Click Me");

JAVA - UNIT 4 5
button.setBounds(50, 100, 80, 30);

// Register ActionListener for the button


button.addActionListener(this);

// Add button to the frame


add(button);

setSize(300, 200);
setLayout(null);
setVisible(true);
}

// Override actionPerformed method


public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}

public static void main(String[] args) {


new ButtonEventExample();
}
}

Explanation:
1. ActionListener Interface:

The ButtonEventExample class implements the ActionListener interface.

2. Registering the Listener:

The button's addActionListener(this) method registers the frame as the


event listener.

3. Handling the Event:

The actionPerformed method is called when the button is clicked.

Window Events: WindowEvent and WindowListener

Example of Handling Window Closing:

import java.awt.*;
import java.awt.event.*;

public class WindowEventExample extends Frame implements Wind


owListener {
public WindowEventExample() {
setTitle("Window Event Example");
setSize(400, 300);

JAVA - UNIT 4 6
// Register WindowListener for the frame
addWindowListener(this);

setVisible(true);
}

public void windowClosing(WindowEvent e) {


System.out.println("Window is closing...");
dispose(); // Close the window
}

// Empty implementations for other methods in WindowListe


ner
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}

public static void main(String[] args) {


new WindowEventExample();
}
}

Explanation:
1. WindowListener Interface:

The WindowEventExample class implements the WindowListener interface.

2. Handling Window Closing:

The windowClosing method is overridden to specify the behavior when the


window is closing.

3. Graphics Class

What is the Graphics Class?


The Graphics class in Java is part of the java.awt package and provides
methods for drawing shapes, text, and images onto GUI components.

It is an abstract class that provides a graphical context for drawing operations.

Drawing Shapes with the Graphics Class

Common Methods for Shapes:


Method Description

JAVA - UNIT 4 7
Draws a line from (x1, y1) to (x2,
drawLine(x1, y1, x2, y2)
y2) .

drawRect(x, y, width, height) Draws an outlined rectangle.


fillRect(x, y, width, height) Draws a filled rectangle.
drawOval(x, y, width, height) Draws an outlined oval.
fillOval(x, y, width, height) Draws a filled oval.
drawPolygon(xPoints, yPoints, nPoints) Draws an outlined polygon.
fillPolygon(xPoints, yPoints, nPoints) Draws a filled polygon.
drawArc(x, y, width, height, startAngle,
arcAngle) Draws an arc.

fillArc(x, y, width, height, startAngle,


arcAngle) Draws a filled arc.

Example of Drawing Shapes:

import java.awt.*;
import javax.swing.*;

public class GraphicsExample extends JPanel {


public void paint(Graphics g) {
// Draw a line
g.drawLine(50, 50, 200, 50);

// Draw a rectangle
g.drawRect(50, 100, 150, 50);

// Draw a filled rectangle


g.fillRect(50, 200, 150, 50);

// Draw an oval
g.drawOval(250, 100, 100, 50);

// Draw a filled oval


g.fillOval(250, 200, 100, 50);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Graphics Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new GraphicsExample());
frame.setVisible(true);
}
}

Color Class

JAVA - UNIT 4 8
Setting Colors:
The Color class is used to define the color of shapes and text in the Graphics

class.

Use setColor(Color color) to set the current drawing color.

Predefined Colors in the Color Class:


Color.RED

Color.GREEN

Color.BLUE

Color.BLACK

Color.YELLOW

Example of Using Colors:

public void paint(Graphics g) {


g.setColor(Color.RED); // Set color to red
g.fillRect(50, 50, 100, 100); // Draw filled red rectang
le

g.setColor(Color.BLUE); // Set color to blue


g.drawOval(200, 50, 100, 100); // Draw outlined blue ova
l
}

Font Class

Changing Text Appearance:


The Font class allows customization of text appearance (font name, style, and
size).

Creating a Font:

Font font = new Font(String name, int style, int size);

name : Font name (e.g., "Arial" , "Times New Roman" )

style : Font style ( Font.PLAIN , Font.BOLD , Font.ITALIC )

size : Font size (e.g., 12 , 16 ).

Example of Drawing Text with a Custom Font:

public void paint(Graphics g) {


Font font = new Font("Arial", Font.BOLD, 20);
g.setFont(font); // Set the font

JAVA - UNIT 4 9
g.setColor(Color.MAGENTA); // Set text color
g.drawString("Hello, Graphics!", 100, 100);
}

Drawing Polygons

Example of Drawing a Polygon:

public void paint(Graphics g) {


int[] xPoints = {100, 150, 200};
int[] yPoints = {100, 50, 100};
int nPoints = 3;

g.setColor(Color.CYAN);
g.drawPolygon(xPoints, yPoints, nPoints); // Draw outlin
ed polygon
g.fillPolygon(xPoints, yPoints, nPoints); // Draw filled
polygon
}

Drawing Arcs

Example of Drawing an Arc:

public void paint(Graphics g) {


g.setColor(Color.ORANGE);
g.drawArc(100, 100, 150, 150, 0, 90); // Quarter circle
arc
g.fillArc(100, 300, 150, 150, 45, 180); // Half-circle a
rc
}

4. Menus

What are Menus in AWT?


Menus in AWT provide a way to create structured options for user interaction,
like in desktop applications (e.g., File, Edit, Help menus).

AWT offers classes like MenuBar , Menu , and MenuItem to build menus.

Key Classes for Menus


1. MenuBar:

Represents the top-level menu bar that holds multiple menus.

Added to a frame using setMenuBar(MenuBar mb) .

JAVA - UNIT 4 10
2. Menu:

Represents a drop-down menu containing multiple menu items.

Can contain MenuItem objects or submenus.

3. MenuItem:

Represents an individual item in a menu.

Triggers actions when clicked.

4. CheckboxMenuItem:

A menu item with a checkbox that can be selected or deselected.

5. PopupMenu:

A menu that appears on a specific user action, such as a right-click.

Creating a Menu in AWT

Example: Basic Menu Creation

import java.awt.*;
import java.awt.event.*;

public class MenuExample extends Frame {


public MenuExample() {
// Create a menu bar
MenuBar mb = new MenuBar();

// Create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");

// Create menu items for the File menu


MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");

// Add menu items to the File menu


fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator(); // Add a separator line
fileMenu.add(exitItem);

// Add action listener for Exit item


exitItem.addActionListener(e -> System.exit(0));

// Create menu items for the Edit menu


MenuItem cutItem = new MenuItem("Cut");
MenuItem copyItem = new MenuItem("Copy");

JAVA - UNIT 4 11
MenuItem pasteItem = new MenuItem("Paste");

// Add menu items to the Edit menu


editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);

// Add menus to the menu bar


mb.add(fileMenu);
mb.add(editMenu);

// Set the menu bar to the frame


setMenuBar(mb);

setTitle("AWT Menu Example");


setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new MenuExample();
}
}

Explanation:
1. MenuBar: A MenuBar object ( mb ) is created and added to the frame using
setMenuBar() .

2. Menus: Two menus, "File" and "Edit," are created using the Menu class.

3. Menu Items: Items like "New," "Open," and "Exit" are created using the
MenuItem class and added to the menus.

4. Action Listener: The "Exit" menu item has an ActionListener to close the
program when clicked.

Adding Submenus

Example: Menu with a Submenu

import java.awt.*;

public class SubmenuExample extends Frame {


public SubmenuExample() {
// Create a menu bar
MenuBar mb = new MenuBar();

// Create a File menu

JAVA - UNIT 4 12
Menu fileMenu = new Menu("File");

// Create menu items


MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");

// Add items to the File menu


fileMenu.add(newItem);
fileMenu.add(openItem);

// Create a submenu for Save


Menu saveMenu = new Menu("Save");
saveMenu.add(new MenuItem("Save As Text"));
saveMenu.add(new MenuItem("Save As PDF"));

// Add the submenu to the File menu


fileMenu.add(saveMenu);

// Add the File menu to the menu bar


mb.add(fileMenu);

// Set the menu bar to the frame


setMenuBar(mb);

setTitle("Submenu Example");
setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new SubmenuExample();
}
}

Explanation:
1. A Menu object named "Save" is created and added to the "File" menu as a
submenu.

2. The submenu contains items like "Save As Text" and "Save As PDF."

3. The structure looks like:

File
├── New
├── Open
├── Save

JAVA - UNIT 4 13
├── Save As Text
└── Save As PDF

Popup Menus

Example: Right-Click Popup Menu

import java.awt.*;
import java.awt.event.*;

public class PopupMenuExample extends Frame {


public PopupMenuExample() {
// Create a popup menu
PopupMenu popup = new PopupMenu();

// Add menu items to the popup menu


MenuItem cut = new MenuItem("Cut");
MenuItem copy = new MenuItem("Copy");
MenuItem paste = new MenuItem("Paste");

popup.add(cut);
popup.add(copy);
popup.add(paste);

// Add popup menu to the frame


add(popup);

// Add mouse listener to display the popup menu


addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(), e.getX(), e.
getY());
}
}
});

setTitle("Popup Menu Example");


setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new PopupMenuExample();
}
}

JAVA - UNIT 4 14
Explanation:
1. PopupMenu:

A PopupMenu object is created and populated with menu items like "Cut,"
"Copy," and "Paste."

2. MouseListener:

A MouseAdapter listens for a right-click ( isPopupTrigger ) to display the popup


menu.

Summary:
MenuBar: Holds multiple menus.

Menu: Contains MenuItem objects and submenus.

MenuItem: Represents individual menu options.

PopupMenu: A context-sensitive menu displayed on user actions like a right-


click.

5. Images in AWT

What are Images in AWT?


AWT provides the Image class and related methods to load and display images
in Java GUI applications.

Images can be loaded from files, URLs, or other sources, and displayed using
components like Canvas or overridden paint() methods in Frame .

Types of Images
1. Raster Images:

Bitmap-based images made up of a grid of pixels.

Examples: .jpg , .png , .gif .

2. Vector Images:

Graphics based on mathematical equations, scalable without losing


quality.

AWT primarily supports raster images.

Displaying Images in AWT

Steps to Display an Image:


1. Load the Image:

Use the Toolkit.getDefaultToolkit().getImage(String fileName) method to load


the image.

2. Draw the Image:

JAVA - UNIT 4 15
Use the Graphics.drawImage() method inside the paint() method to display
the image.

Example: Loading and Displaying an Image

import java.awt.*;

public class ImageExample extends Frame {


Image img;

public ImageExample() {
// Load the image
img = Toolkit.getDefaultToolkit().getImage("example.j
pg");

// Set frame properties


setTitle("AWT Image Example");
setSize(500, 500);
setVisible(true);
}

public void paint(Graphics g) {


// Draw the image
g.drawImage(img, 50, 50, this);
}

public static void main(String[] args) {


new ImageExample();
}
}

Key Methods for Image Handling


1. Loading an Image:

Toolkit.getDefaultToolkit().getImage(String filename) :

Loads an image from a file.

Toolkit.getDefaultToolkit().getImage(URL url) :

Loads an image from a URL.

2. Drawing an Image:

Graphics.drawImage(Image img, int x, int y, ImageObserver observer) :

Draws the specified image at (x, y) .

3. Scaling an Image:

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

JAVA - UNIT 4 16
Scales the image to the specified dimensions.

Example:

Image scaledImg = img.getScaledInstance(200, 200, Imag


e.SCALE_SMOOTH);

Advanced Example: Resizing and Handling Image

import java.awt.*;

public class ScaledImageExample extends Frame {


Image img;

public ScaledImageExample() {
// Load and scale the image
img = Toolkit.getDefaultToolkit().getImage("example.j
pg");
img = img.getScaledInstance(300, 200, Image.SCALE_SMO
OTH);

// Set frame properties


setTitle("Scaled Image Example");
setSize(500, 400);
setVisible(true);
}

public void paint(Graphics g) {


// Draw the scaled image
g.drawImage(img, 100, 100, this);
}

public static void main(String[] args) {


new ScaledImageExample();
}
}

Using ImageObserver
The ImageObserver interface is used to monitor the loading and rendering of
images.

The Frame class already implements ImageObserver , so we can pass this as the
observer while drawing the image.

Summary:

JAVA - UNIT 4 17
AWT makes it easy to load and display raster images using the Toolkit and
Graphics classes.

Images can be resized and drawn at specific positions using drawImage() and
getScaledInstance() .

Advanced features like ImageObserver provide control over image loading and
rendering.

6. Java Stream Class

What are Streams in Java?


Streams in Java are used to perform input and output operations, such as
reading data from files, writing data to files, or handling console input/output.

A stream is a sequence of data, and Java categorizes streams into byte


streams and character streams.

Types of Streams
1. Byte Streams:

Used to handle binary data, such as reading or writing image or video files.

Classes:

InputStream for reading binary data.

OutputStream for writing binary data.

2. Character Streams:

Used to handle textual data (characters).

Classes:

Reader for reading characters.

Writer for writing characters.

Byte Streams

Common Classes in Byte Streams:


Class Description
FileInputStream Reads bytes from a file.
FileOutputStream Writes bytes to a file.
BufferedInputStream Reads bytes from a buffer to improve performance.
BufferedOutputStream Writes bytes to a buffer for performance.

Example of Byte Stream:

import java.io.*;

JAVA - UNIT 4 18
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream in = new FileInputStream("input.
txt");
FileOutputStream out = new FileOutputStream("out
put.txt")) {
int data;
while ((data = in.read()) != -1) {
out.write(data); // Writes data to output.txt
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Character Streams

Common Classes in Character Streams:


Class Description
FileReader Reads characters from a file.
FileWriter Writes characters to a file.
BufferedReader Reads text from a buffer for efficiency.
BufferedWriter Writes text to a buffer for efficiency.

Example of Character Stream:

import java.io.*;

public class CharacterStreamExample {


public static void main(String[] args) {
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.tx
t")) {
int data;
while ((data = reader.read()) != -1) {
writer.write(data); // Writes data to output.
txt
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}

JAVA - UNIT 4 19
}
}

Buffered Streams

Why Use Buffered Streams?


Buffered streams improve performance by reducing the number of read/write
operations performed on the disk.

Example of Buffered Stream:

import java.io.*;

public class BufferedStreamExample {


public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new F
ileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new F
ileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Add a newline
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Summary of Key Points:


Byte Streams: Handle binary data; use InputStream and OutputStream classes.

Character Streams: Handle textual data; use Reader and Writer classes.

Buffered Streams: Enhance performance for both byte and character streams.

JAVA - UNIT 4 20

You might also like