0% found this document useful (0 votes)
4 views28 pages

Abstract Window Tool Kit

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, with platform-dependent components that utilize the underlying OS resources. It includes various components and containers, such as Frame, Panel, and Dialog, and supports event handling through listeners for user interactions. The document also covers inner classes, anonymous inner classes, and adapter classes for handling events more efficiently.

Uploaded by

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

Abstract Window Tool Kit

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, with platform-dependent components that utilize the underlying OS resources. It includes various components and containers, such as Frame, Panel, and Dialog, and supports event handling through listeners for user interactions. The document also covers inner classes, anonymous inner classes, and adapter classes for handling events more efficiently.

Uploaded by

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

AWT

(Abstract Window Tool kit)


Java AWT (Abstract Window Toolkit) :
It is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java.
Note:
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. (i.e. 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.)
• AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
• All the elements like the button, text fields, scroll bars, etc. are called
components. In AWT API, these components are defined as classes.
Container
• The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc.
• The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
Types of containers:
There are four types of containers in Java AWT:
• Window
• Panel
• Frame
• 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.
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.
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.
Key Differences:
In practice, use Window or Frame for main application windows and Panel for
grouping components within those windows.

Feature Window (e.g., Frame, Dialog) Panel

Type Top-level container Lightweight container

Standalone Yes No, needs a parent container

Title Bar Yes (in Frame) No

Close Button Yes (in Frame) No

Use Case Main application window Organizing components within a window

Event Handling Supports WindowListener Does not support window events


Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

Sets the size (width and height) of the


public void setSize(int width,int height) component.

Defines the layout manager for the


public void setLayout(LayoutManager m) component.

Changes the visibility of the component,


public void setVisible(boolean status) by default false.
// adding components into frame
import java.awt.*; f.add(b);
class AWTExample2 { f.add(l);
AWTExample2() { f.add(t);

Frame f = new Frame(); // frame size 300 width and 300 height

Label l = new Label("Employee id:"); f.setSize(400,300);

Button b = new Button("Submit"); // setting the title of frame

f.setTitle("Employee info");
TextField t = new TextField();
// no layout

f.setLayout(null);
// setting position of above components in the frame
// setting visibility of frame
l.setBounds(20, 80, 80, 30);
f.setVisible(true);
t.setBounds(20, 100, 80, 30);
}
b.setBounds(100, 100, 80, 30); public static void main(String args[]) {

AWTExample2 awt_obj = new AWTExample2();


Event Handling
Event handling : It is a procedure that controls an event and performs
appropriate action if it occurs. The code or set of instructions used to
implement it is known as the Event handler.
It consists of two major components:
1. The event source
2. The event listener.
Event : it represents the change in the state of any object.
Note: Events occur when the user interacts with the interface.
Ex:
• Clicking a button
• moving the mouse
• typing a character
• selecting an item from a list
• scrolling the page

Event Source: it is an object where the event occurs.


Ex:
Event Source : Description
Button : Generates action events when the button is pressed.
Check box : Generates item events when the check box is selected or deselected.
Choice : Generates item events when the choice is changed.
List : Generates action events when an item is double-clicked; generates item events when an item
is selected or deselected.
• A source must register listeners so they can receive notifications
about specific types of events."
• Each type of event has its own registration method.
The general form:
public void addTypeListener(TypeListener el)
Ex:
• addActionListener
• addKeyListener( )
• addMouseListener
• addMouseMotionListener( )
• A listener can also unregister from a source using below method.
public void removeTypeListener(TypeListener el)
Event Listener: A listener is an object that is notified when an event occurs.
It has two major requirements.
• First, it must have been registered with one or more sources to receive
notifications about specific types of events.
• Second, it must implement methods to receive and process these notifications.
Note: Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package
Ex:
•ActionListener - Listens for action events (e.g., button clicks).
•MouseListener - Detects mouse events like clicks, enters, and exits.
•KeyListener - Monitors keyboard events like key presses and releases.
•WindowListener - Responds to window events such as opening, closing, minimizing, etc.
•FocusListener - Tracks focus gained or lost on components.
•ItemListener - Listens for changes in the state of items (e.g., checkboxes).
•ChangeListener - Used for listening to changes in components (e.g., sliders).
ActionListener Interface
This interface defines the actionPerformed( ) method.
that is invoked when an action event occurs.
Its general form is shown here:
void actionPerformed(ActionEvent ae)

The ItemListener Interface


This interface defines the itemStateChanged( ) method that is invoked
when the state of an item changes.
Its general form is shown here:
void itemStateChanged(ItemEvent ie)
KeyListener Interface
This interface defines three methods.
1. keyPressed( ) - when a key is pressed.
2. keyReleased( ) – when key is released.
3. keyTyped( ) - when a character has been entered.
The general forms of these methods are shown here:
• void keyPressed(KeyEvent ke)
• void keyReleased(KeyEvent ke)
• void keyTyped(KeyEvent ke
MouseListener Interface
This interface defines five methods.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me) - . If the mouse is pressed and
released at the same point
void mouseEntered(MouseEvent me) - When the mouse enters a
component,
void mouseExited(MouseEvent me) - When it leaves the component
void mousePressed(MouseEvent me) – when mouse pressed
void mouseReleased(MouseEvent me)- when mouse released.
MouseMotionListener Interface:
This interface defines two methods.
• The mouseDragged( ) method is called multiple times as the mouse is dragged.
• The mouseMoved( ) method is called multiple times as the mouse is moved.
Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
TextListener Interface
This interface defines the textChanged( ) method that is invoked when a
change occurs in a text area or text field.
Its general form is shown here:
void textChanged(TextEvent te)
WindowListener Interface
The general forms of these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
import java.awt.*; // Create a label to display the output message
Label outputLabel = new Label();
import java.awt.event.*;
frame.add(outputLabel);

public class ButtonClickExample { // Add an ActionListener to the button


public static void main(String[] args) { registerButton.addActionListener(new ActionListener() {
@Override
// Create a new frame
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame("Registration Example"); // Get the text entered in the text field
frame.setSize(400, 200); String name = nameField.getText();
frame.setLayout(new FlowLayout()); // Display the message in the output label
outputLabel.setText("Hello " + name + ", you are registered!");
}
// Create a label to prompt for name });
Label nameLabel = new Label("Enter Name:");
// Add a window listener to close the frame
frame.add(nameLabel);
frame.addWindowListener(new WindowAdapter() {
@Override
// Create a text field for name input public void windowClosing(WindowEvent we) {
TextField nameField = new TextField(20); frame.dispose();
}
frame.add(nameField);
});

// Create a button to register (Source) // Set frame visibility to true


Button registerButton = new Button("Register"); frame.setVisible(true);
}
frame.add(registerButton);
Adapter Classes:
• An adapter class provides an empty implementation of all methods in
an event listener interface.
• Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event
listener interface.
import java.awt.*; }
import java.awt.event.*; }

// Main class extending Frame // MouseAdapter class for handling mouse click events
public class AdapterDemoFrame extends Frame { class MyMouseAdapter extends MouseAdapter {
public AdapterDemoFrame() { AdapterDemoFrame adapterDemoFrame;
// Set frame properties
setTitle("Adapter Demo"); public MyMouseAdapter(AdapterDemoFrame adapterDemoFrame) {
setSize(300, 100); this.adapterDemoFrame = adapterDemoFrame;
setVisible(true); }

// Add mouse listeners // Handle mouse clicked event


addMouseListener(new MyMouseAdapter(this)); public void mouseClicked(MouseEvent me) {
addMouseMotionListener(new MyMouseMotionAdapter(this)); adapterDemoFrame.showStatus("Mouse clicked");
}
// Window close event }
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) { // MouseMotionAdapter class for handling mouse drag events
System.exit(0); class MyMouseMotionAdapter extends MouseMotionAdapter {
} AdapterDemoFrame adapterDemoFrame;
});
} public MyMouseMotionAdapter(AdapterDemoFrame adapterDemoFrame) {
this.adapterDemoFrame = adapterDemoFrame;
// Method to show status in the frame's title bar }
public void showStatus(String message) {
setTitle(message); // Handle mouse dragged event
Innerclass
Classes:
OuterClass {
int x = 10;
An inner class
voidisP(){
a class defined
System.out.println("hi");
within another
} class.
class InnerClass {
Advantage of Javaint yinner
= 5; classes:
• it can access void
all
p();
Q(){
the members
(data members and methods)
System.out.println("X is "+ x);
of the outer
}
class,
} including

private.
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
myInner.Q();
}
}
// This applet does NOT use an inner class.
import java.applet.*; // Inner class demo.
import java.awt.event.*; import java.applet.*;
/* import java.awt.event.*;
<applet code="MousePressedDemo" width=200 height=100> /*
</applet> <applet code="InnerClassDemo" width=200 height=100>
*/ </applet>
public class MousePressedDemo extends */
Applet { public class InnerClassDemo extends Applet {
public void init() { public void init() {
addMouseListener(new MyMouseAdapter(this)); addMouseListener(new MyMouseAdapter());
} }
} class MyMouseAdapter extends MouseAdapter {
class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) {
MousePressedDemo mousePressedDemo; showStatus("Mouse Pressed");
public MyMouseAdapter(MousePressedDemo }
mousePressedDemo) { }
this.mousePressedDemo = mousePressedDemo;
}
}
public void mousePressed(MouseEvent me) {
mousePressedDemo.showStatus("Mouse Pressed.");
}
}
Anonymous Inner Class
• A class that has no name is known as an anonymous inner class.
• It should be used if you have to override a method of class or interface.
• Java Anonymous inner class can be created in two ways:
Ex:
1. Class (may be abstract or concrete). abstract class Person{
2. Interface abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person() {
void eat(){
System.out.println("nice fruits");
}

};
p.eat();
}
}
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
MOUSE EVENTS
import java.awt.*; // Handle mouse entered. repaint();
import java.awt.event.*; @Override }
import javax.swing.*; public void mouseEntered(MouseEvent me) {
mouseX = 0; // Handle mouse dragged.
public class MouseEvents extends JFrame implements MouseListener, mouseY = 10; @Override
MouseMotionListener { msg = "Mouse entered."; public void mouseDragged(MouseEvent me) {
String msg = ""; repaint(); mouseX = me.getX();
int mouseX = 0, mouseY = 0; // coordinates of mouse } mouseY = me.getY();
msg = "*";
public MouseEvents() { // Handle mouse exited. setTitle("Dragging mouse at " + mouseX + ", " + mouseY);
// Set up the frame @Override repaint();
setTitle("Mouse Events Example"); public void mouseExited(MouseEvent me) { }
setSize(400, 300); mouseX = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mouseY = 10; // Handle mouse moved.
msg = "Mouse exited."; @Override
// Add mouse listeners repaint(); public void mouseMoved(MouseEvent me) {
addMouseListener(this); } setTitle("Moving mouse at " + me.getX() + ", " + me.getY());
addMouseMotionListener(this); }
// Handle button pressed.
// Make the frame visible @Override // Display msg at current X,Y location.
setVisible(true); public void mousePressed(MouseEvent me) { @Override
} mouseX = me.getX(); public void paint(Graphics g) {
mouseY = me.getY(); super.paint(g); // call the superclass paint method
// Handle mouse clicked. msg = "Down"; g.drawString(msg, mouseX, mouseY);
@Override repaint(); }
public void mouseClicked(MouseEvent me) { }
mouseX = 0; public static void main(String[] args) {
mouseY = 10; // Handle button released. new MouseEvents();
msg = "Mouse clicked at (" + me.getX() + ", " + me.getY() + ")"; @Override }
repaint(); public void mouseReleased(MouseEvent me) { }
mouseX = me.getX();
} mouseY = me.getY();
msg = "Up";
KEY EVENTS
import java.awt.*; }
import java.awt.event.*;
public class SimpleKeyFrame extends Frame implements KeyListener { // Handle key released event
String msg = ""; public void keyReleased(KeyEvent ke) {
int X = 10, Y = 50; // output coordinates setTitle("Key Up");
}
public SimpleKeyFrame() {
// Set the title and size of the Frame // Handle key typed event and update the message
super("SimpleKey Frame Example"); public void keyTyped(KeyEvent ke) {
setSize(300, 100); msg += ke.getKeyChar();
repaint();
// Add the KeyListener to the Frame }
addKeyListener(this);
// Display keystrokes on the frame
// Set up a WindowListener to handle closing the window public void paint(Graphics g) {
addWindowListener(new WindowAdapter() { g.drawString(msg, X, Y);
public void windowClosing(WindowEvent we) { }
System.exit(0);
} // Main method to launch the frame
}); public static void main(String[] args) {
setVisible(true); new SimpleKeyFrame();
} }
// Handle key pressed event }
public void keyPressed(KeyEvent ke) {
setTitle("Key Down");

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy