0% found this document useful (0 votes)
6 views66 pages

java1-unit3

Java AWT (Abstract Window Toolkit) is an API for developing platform-independent GUI applications in Java, utilizing components that are platform-dependent. It includes various elements such as components, containers, layout managers, and event handling, allowing developers to create interactive applications. AWT also features adapter classes to simplify event handling and provides examples of creating GUI applications through inheritance and association.

Uploaded by

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

java1-unit3

Java AWT (Abstract Window Toolkit) is an API for developing platform-independent GUI applications in Java, utilizing components that are platform-dependent. It includes various elements such as components, containers, layout managers, and event handling, allowing developers to create interactive applications. AWT also features adapter classes to simplify event handling and provides examples of creating GUI applications through inheritance and association.

Uploaded by

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

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 java.awt 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:
Java Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

Pros of using Adapter classes:

 It assists the unrelated classes to work combined.


 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event


packages. The Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes


Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes


Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example

In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.

AdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. public class AdapterExample {
6. // object of Frame
7. Frame f;
8. // class constructor
9. AdapterExample() {
10. // creating a frame with the title
11. f = new Frame ("Window Adapter");
12. // adding the WindowListener to the frame
13. // overriding the windowClosing() method
14. f.addWindowListener (new WindowAdapter() {
15. public void windowClosing (WindowEvent e) {
16. f.dispose();
17. }
18. });
19. // setting the size, layout and
20. f.setSize (400, 400);
21. f.setLayout (null);
22. f.setVisible (true);
23. }
24.
25. // main method
26. public static void main(String[] args) {
27. new AdapterExample();
28. }
29. }

Output:

Java MouseAdapter Example

In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.

MouseAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits the MouseAdapter class
5. public class MouseAdapterExample extends MouseAdapter {
6. // object of Frame class
7. Frame f;
8. // class constructor
9. MouseAdapterExample() {
10. // creating the frame with the title
11. f = new Frame ("Mouse Adapter");
12. // adding MouseListener to the Frame
13. f.addMouseListener(this);
14. // setting the size, layout and visibility of the frame
15. f.setSize (300, 300);
16. f.setLayout (null);
17. f.setVisible (true);
18. }
19. // overriding the mouseClicked() method of the MouseAdapter class
20. public void mouseClicked (MouseEvent e) {
21. // creating the Graphics object and fetching them from the Frame object using getGraphi
cs() method
22. Graphics g = f.getGraphics();
23. // setting the color of graphics object
24. g.setColor (Color.BLUE);
25. // setting the shape of graphics object
26. g.fillOval (e.getX(), e.getY(), 30, 30);
27. }
28. // main method
29. public static void main(String[] args) {
30. new MouseAdapterExample();
31. }
32. }

Output:

Java MouseMotionAdapter Example

In the following example, we are implementing the MouseMotionAdapter class and its different
methods to listen to the mouse motion events in the Frame window.

MouseMotionAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits the MouseMotionAdapter class
5. public class MouseMotionAdapterExample extends MouseMotionAdapter {
6. // object of Frame class
7. Frame f;
8. // class constructor
9. MouseMotionAdapterExample() {
10. // creating the frame with the title
11. f = new Frame ("Mouse Motion Adapter");
12. // adding MouseMotionListener to the Frame
13. f.addMouseMotionListener (this);
14. // setting the size, layout and visibility of the frame
15. f.setSize (300, 300);
16. f.setLayout (null);
17. f.setVisible (true);
18. }
19. // overriding the mouseDragged() method
20. public void mouseDragged (MouseEvent e) {
21. // creating the Graphics object and fetching them from the Frame object using getGraphi
cs() method
22. Graphics g = f.getGraphics();
23. // setting the color of graphics object
24. g.setColor (Color.ORANGE);
25. // setting the shape of graphics object
26. g.fillOval (e.getX(), e.getY(), 20, 20);
27. }
28. public static void main(String[] args) {
29. new MouseMotionAdapterExample();
30. }
31. }

Output:

Java KeyAdapter Example

In the following example, we are implementing the KeyAdapter class and its method.

KeyAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits the KeyAdapter class
5. public class KeyAdapterExample extends KeyAdapter {
6. // creating objects of Label, TextArea and Frame
7. Label l;
8. TextArea area;
9. Frame f;
10. // class constructor
11. KeyAdapterExample() {
12. // creating the Frame with title
13. f = new Frame ("Key Adapter");
14. // creating the Label
15. l = new Label();
16. // setting the location of label
17. l.setBounds (20, 50, 200, 20);
18. // creating the text area
19. area = new TextArea();
20. // setting the location of text area
21. area.setBounds (20, 80, 300, 300);
22. // adding KeyListener to text area
23. area.addKeyListener(this);
24. // adding the label and text area to frame
25. f.add(l);
26. f.add(area);
27. // setting the size, layout and visibility of frame
28. f.setSize (400, 400);
29. f.setLayout (null);
30. f.setVisible (true);
31. }
32. // overriding the keyReleased() method
33. public void keyReleased (KeyEvent e) {
34. // creating the String object to get the text fromTextArea
35. String text = area.getText();
36. // splitting the String into words
37. String words[] = text.split ("\\s");
38. // setting the label text to print the number of words and characters of given string
39. l.setText ("Words: " + words.length + " Characters:" + text.length());
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyAdapterExample();
44. }
45. }

Output:
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


Defines the layout manager for the component.
m)

Changes the visibility of the component, by default


public void setVisible(boolean status)
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.

AWTExample1.java

1. // importing Java AWT class


2. import java.awt.*;
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. b.setBounds(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.

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.

AWTExample2.java

1. // importing Java AWT class


2. import java.awt.*;
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. l.setBounds(20, 80, 80, 30);
24. t.setBounds(20, 100, 80, 30);
25. b.setBounds(100, 100, 80, 30);
26.
27. // adding components into frame
28. f.add(b);
29. f.add(l);
30. f.add(t);
31.
32. // frame size 300 width and 300 height
33. f.setSize(400,300);
34.
35. // setting the title of frame
36. f.setTitle("Employee info");
37.
38. // no layout
39. f.setLayout(null);
40.
41. // setting visibility of frame
42. f.setVisible(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

Java's Abstract Window Toolkit (AWT) provides a set of classes for creating graphical user
interfaces and painting graphics.

Inner Class in Java


Types of Inner Class
In Java, inner class refers to the class that is declared inside class or interface which were
mainly introduced, to sum up, same logically relatable classes as Java is object-oriented so
bringing it closer to the real world. Now geeks you must be wondering why they were
introduced?

Java Inner Class

A Java inner class is a class that is defined inside another class. The concept of inner class
works with nested Java classes where outer and inner classes are used. The main class in which
inner classes are defined is known as the outer class and all other classes which are inside the
outer class are known as Java inner classes.

Nested Classes

In Java, just like methods, variables of a class too can have another class as its member. Writing
a class within another is allowed in Java. The class written within is called the nested class, and
the class that holds the inner class is called the outer class.

Syntax

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.

class Outer_Demo {
class Inner_Demo {
}
}

Nested classes are divided into two types −

 Non-static nested classes − These are the non-static members of a class.


 Static nested classes − These are the static members of a class.
Types of Java Inner Classes

Inner classes are of three types depending on how and where you define them. They are −

 Inner Class
 Method-local Inner Class
 Anonymous Inner Class

Creating an Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.

Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.

Example: Creating an inner class in Java


Open Compiler

class Outer_Demo {
int num;

// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}

// Accessing he inner class from the method within


void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class,
display_Inner() is the method inside which we are instantiating the inner class, and this method
is invoked from the main method.

If you compile and execute the above program, you will get the following result −

Output
This is an inner class.
Accessing the Private Members

As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return the
private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue() method
of the inner class.

To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using
the object of the outer class, following is the way in which you can instantiate the inner class.

Outer_Demo outer = new Outer_Demo();


Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();

The following program shows how to access the private members of a class using inner class.

Example: Accessing the Private Members Using Inner Class


class Outer_Demo {
// private variable of the outer class
private int num = 175;

// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}

public class My_class2 {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Instantiating the inner class


Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}

If you compile and execute the above program, you will get the following result −
Output
This is the getnum method of the inner class: 175
Method-local Inner Class

In Java, we can write a class within a method and this will be a local type. Like local variables,
the scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.

Example: Method-local Inner Class


Open Compiler

public class Outerclass {


// instance method of the outer class
void my_Method() {
int num = 23;

// method-local inner class


class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class

// Accessing the inner class


MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}

public static void main(String args[]) {


Outerclass outer = new Outerclass();
outer.my_Method();
}
}

If you compile and execute the above program, you will get the following result −

Output
This is method inner class 23
Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner class. In case of
anonymous inner classes, we declare and instantiate them at the same time. Generally, they are
used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows −

Syntax: Anonymous Inner Class


AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using anonymous inner
class.

Example: Anonymous Inner Class


Open Compiler

abstract class AnonymousInner {


public abstract void mymethod();
}

public class Outer_class {

public static void main(String args[]) {


AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}

If you compile and execute the above program, you will get the following result −

Output
This is an example of anonymous inner class

In the same way, you can override the methods of the concrete class as well as the interface
using an anonymous inner class.

Anonymous Inner Class as Argument

Generally, if a method accepts an object of an interface, an abstract class, or a concrete class,


then we can implement the interface, extend the abstract class, and pass the object to the
method. If it is a class, then we can directly pass it to the method.

But in all the three cases, you can pass an anonymous inner class to the method. Here is the
syntax of passing an anonymous inner class as a method argument −

obj.my_Method(new My_Class() {
public void Do() {
.....
.....
}
});

The following program shows how to pass an anonymous inner class as a method argument.

Example
Open Compiler

// interface
interface Message {
String greet();
}
public class My_class {
// method which accepts the object of interface Message
public void displayMessage(Message m) {
System.out.println(m.greet() +
", This is an example of anonymous inner class as an argument");
}

public static void main(String args[]) {


// Instantiating the class
My_class obj = new My_class();

// Passing an anonymous inner class as an argument


obj.displayMessage(new Message() {
public String greet() {
return "Hello";
}
});
}
}

If you compile and execute the above program, it gives you the following result −

Output
Hello, This is an example of anonymous inner class as an argument
Static Nested Class

A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of the
outer class. The syntax of static nested class is as follows −

Syntax
class MyOuter {
static class Nested_Demo {
}
}

Instantiating a static nested class is a bit different from instantiating an inner class. The
following program shows how to use a static nested class.

Example
Open Compiler

public class Outer {


static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}

public static void main(String args[]) {


Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
If you compile and execute the above program, you will get the following result −

Output
This is my nested class

There are certain advantages associated with inner classes are as follows:

 Making code clean and readable.

 Private methods of the outer class can be accessed, so bringing a new dimension and
making it closer to the real world.

 Optimizing the code module.

Types of Inner Classes

There are basically four types of inner classes in java.

1. Nested Inner Class

2. Method Local Inner Classes

3. Static Nested Classes

4. Anonymous Inner Classes

Java AWT Classes


User Interface Components

The user interface components in Abstract Window Toolkit (AWT) include buttons,
checkboxes, labels, text fields, and containers. AWT is a Java API that helps create graphical
user interfaces (GUIs) for Java applications.
User interface components in AWT

Button: A component that can be used in a GUI


Checkbox: A graphical component that can be in an "on" or "off" state
Label: A component that can be used in a GUI
Text field: A component that allows users to enter text
Container: A component that can contain other components like buttons, text fields, and labels
Frame: A container class that extends the Container class
Panel: A container class that extends the Container class
Dialog: A container class that extends the Container class
SystemTray: A class that represents the system tray for a desktop
TextArea: A multi-line region that displays text
TextComponent: A superclass of any component that allows the editing of some text
AWT also includes layout managers, graphics and imaging tools, and data transfer classes.
Additional information

 AWT is part of the Java Foundation Classes


 AWT is platform-dependent
 AWT manages events such as click and hover
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 Label.LEFT, Label.CENTER,
and Label.RIGHT.

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 System.exit(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:

. 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: Label.LEFT, Label.RIGHT, Label.CENTER.
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.
A
WT Scrollbar Class
Menus and Scroll Panes
Java Delegation Model:
Delegation event model

1.Source

2.Listener

You might also like