java1-unit3
java1-unit3
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 (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.
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.
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.
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.
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.
AdapterExample.java
Output:
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
Output:
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
Output:
In the following example, we are implementing the KeyAdapter class and its method.
KeyAdapterExample.java
Output:
Useful Methods of Component Class
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the component.
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
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
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
Java's Abstract Window Toolkit (AWT) provides a set of classes for creating graphical user
interfaces and painting graphics.
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 {
}
}
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 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.
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
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.
The following program shows how to access the private members of a class using inner class.
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
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.
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 −
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.
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");
}
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
Output
This is my nested class
There are certain advantages associated with inner classes are as follows:
Private methods of the outer class can be accessed, so bringing a new dimension and
making it closer to the real world.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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).
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.
Label Constructors:
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.
Button Constructors:
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:
Canvas Constructor:
Canvas Methods:
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.
Checkbox Constructor
Methods of Checkbox
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
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.
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.
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.
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