Unit 4 JAVA
Unit 4 JAVA
Unit - IV
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.
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.
Note: Container can be added inside another container as it is type of component.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box. The Window
class extends the Container class, which means it can contain other components, such as buttons, labels, and
text fields.
Dr.Tejinder Kaur (Associate Professor)
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping other
components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when clicked on. Button Class is used
for creating a labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with show click here as the
value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessible
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable
Note: CheckboxGroup enables the use of radio buttons in AWT.
6. Java AWT Choice
The object of the Choice class is used to show a popup menu of choices.
Dr.Tejinder Kaur (Associate Professor)
Syntax of WindowListener
public interface WindowListener extends EventListener
There are seven methods associated with WindowListener as mentioned below:
1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus
7. Java Adapter classes
Java adapter classes provide the default implementation of listener interfaces.
8. Close AWT Window
At the end we will need to Close AWT Window, So to perform this task we will use dispose() method. This
method releases the resources associated with the window and also removes it from the screen.
Java AWT Examples
Here are some Java AWT examples:
Hello World in Java AWT
Java AWT Program to create Button
1. Hello World in Java AWT
Hello, World is was the first step in learning Java. So, let us program our first Program in Java AWT as Hello
World using Labels and Frames.
Below is the implementation of the above method:
Java
// Driver Class
public class AWT_Example {
// main function
public static void main(String[] args)
{
// Declaring a Frame and Label
Frame frame = new Frame("Basic Program");
Label label = new Label("Hello World!");
After the applet, the type of window we will most often create is derived from Frame. We will use it to create
child windows within applets, and top-level or child windows for applications. It creates a standard -style
window. Following are two of Frame’s constructors:
Frame( )
Frame(String title)
The first form creates a standard window that does not contain a title. The second form creates a window with
the title specified by title. Note that we cannot specify the dimensions of the window. Instead, we must set the
size of the window after it has been created.
The setSize( ) method is used to set the dimensions of the window. Its signature is shown below:
The new size of the window is specified by ‘newWidth’ and ‘newHeight’, or by the ‘width’ and ‘height’ fields
of the Dimension object passed in ‘newSize’. The dimensions are specified in terms of pixels. The getSize( )
method is used to obtain the current size of a window. Its signature is:
Dimension getSize( )
This method returns the current size of the window contained within the ‘width’ and ‘height’ fields of a
Dimension object.
After a frame window has been created, it will not be visible until we call setVisible( ). Its signature is:
void set Visible(boolean visible flag)
The component is visible if the argument to this method is true. Otherwise, it is hidden.
We can change the title in a frame window using setTitle( ), which has this general form:
void setTitle(String new title)
Here, ‘new title’ is the new title for the window.
When using a frame window, our program must remove that window from the screen when it is closed, by
calling set Visible(false). To intercept a window close event, we must implement the window closing( ) method
of the Window Listener interface. Inside window Closing(), we must remove the window from the screen.
AWT CONTROLS
UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we
will cover in this tutorial.
Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
Behavior: These are events which occur when the user interacts with UI elements. This part will be
covered in Event Handling chapter.
2 Button
This class creates a labeled button.
3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
5 List
The List component presents the user with a scrolling list of text items.
6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of text.
8 Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.
Canvas
9
A Canvas control represents a rectangular area where application can draw something or can receive inputs created by
user.
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
12 Dialog
A Dialog control represents a top-level window with a title and a border used to take some form of input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are the
following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
Dr.Tejinder Kaur (Associate Professor)
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
The Dialog control represents a top level window with a border and a title used to take some form of input from
the user. It inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't
have.
The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse activity,
clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality to the user.
This is known as event handling.
In this section, we will discuss event processing and how to implement the delegation event model in Java. We
will also discuss the different components of an Event Model.
Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which is
an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch and
Dr.Tejinder Kaur (Associate Professor)
process GUI events for a program, it should hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event processing.
But, the modern approach for event processing is based on the Delegation Model. It defines a standard and
compatible mechanism to generate and process events. In this model, a source generates an event and forwards
it to one or more listeners. The listener waits until it receives an event. Once it receives the event, it is processed
by the listener and returns it. The UI elements are able to delegate the processing of an event to a separate
function.
The key advantage of the Delegation Event Model is that the application logic is completely separated from the
interface logic.
In this model, the listener must be connected with a source to receive the event notifications. Thus, the events
will only be received by the listeners who wish to receive them. So, this approach is more convenient than the
inheritance-based event model (in Java 1.0).
In the older model, an event was propagated up the containment until a component was handled. This needed
components to receive events that were not processed, and it took lots of time. The Delegation Event model
overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be generated as a reaction of a user
while interacting with GUI elements. Some of the event generation activities are moving the mouse pointer,
clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can also consider
many other user operations as events.
Dr.Tejinder Kaur (Associate Professor)
The Events may also occur that may be not related to user interaction, such as a timer expires, counter exceeded,
system failures, or a task is completed, etc. We can define events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal state of the
object is changed. The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each event contains its registration
method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener. For
example, for a keyboard event listener, the method will be called as addKeyListener(). For the mouse event
listener, the method will be called as addMouseMotionListener(). When an event is triggered using the respected
source, all the events will be notified to registered listeners and receive the event object. This process is known
as event multicasting. In few cases, the event notification will only be sent to listeners that register to receive
them.
From the above syntax, the Type is the name of the event, and e2 is the event listener's reference. When the
specified event occurs, it will be notified to the registered listener. This process is known as unicasting events.
A source should contain a method that unregisters a specific type of event from the listener if not needed. Below
is an example of the method that will remove the event from the listener.
From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to
remove the keyboard listener, the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the events. For example, the
Component class contains the methods to operate on the different types of events, such as adding or removing
them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it
must be registered with a source; however, it can be registered with several resources to receive notification
about the events. Second, it must implement the methods to receive and process the received notifications.
Types of Events
The foreground events are those events that require direct interaction of the user. These types of events are
generated as a result of user interaction with the GUI component. For example, clicking on a button, mouse
movement, pressing a keyboard key, selecting an option from the list, etc.
The Background events are those events that result from the interaction of the end-user. For example, an
Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over the events and
responses.
The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based event model using
AWT to resolve the event problems. It provides a convenient mechanism to support complex Java programs.
Design Goals
o It provides robust event handling program code which is less error-prone (strong compile-time
checking)
o It is Flexible, can enable different types of application models for event flow and propagation.
o It enables run-time discovery of both the component-generated events as well as observable events.
o It provides support for the backward binary compatibility with the previous model.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
Dr.Tejinder Kaur (Associate Professor)
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18. }
19.
20. class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
Dr.Tejinder Kaur (Associate Professor)
Output:
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system
generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of events.
An event is an action that calls a function or may cause another event. Event handlers are functions that tell how
to respond to an event.
Mouse events
Keyboard events
Dr.Tejinder Kaur (Associate Professor)
Mouse events occur with mouse movements in forms and controls. Following are the various mouse events
related with a Control class −
The event handlers of the mouse events get an argument of type MouseEventArgs. The MouseEventArgs object
is used for handling mouse events. It has the following properties −
Example
Following is an example, which shows how to handle mouse events. Take the following steps −
Add three labels, three text boxes and a button control in the form.
Change the text properties of the labels to - Customer ID, Name and Address, respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively.
Change the text property of the button to 'Submit'.
Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it
will show the following window −
Try to enter text in the text boxes and check the mouse events −
Dr.Tejinder Kaur (Associate Professor)
Following are the various keyboard events related with a Control class −
KeyDown − occurs when a key is pressed down and the control has focus
KeyPress − occurs when a key is pressed and the control has focus
KeyUp − occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This object has
the following properties −
Example
Let us continue with the previous example to show how to handle keyboard events. The code will verify that the
user enters some numbers for his customer ID and age.
Add a label with text Property as 'Age' and add a corresponding text box named txtAge.
Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtID.KeyUp
Dr.Tejinder Kaur (Associate Professor)
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it
will show the following window −
If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning message box and
clears the respective text −
Dr.Tejinder Kaur (Associate Professor)
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.
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.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
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:
Dr.Tejinder Kaur (Associate Professor)
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
22. // creating the Graphics object and fetching them from the Frame object using getGraphics() method
23. Graphics g = f.getGraphics();
24. // setting the color of graphics object
25. g.setColor (Color.BLUE);
26. // setting the shape of graphics object
27. g.fillOval (e.getX(), e.getY(), 30, 30);
28. }
29. // main method
30. public static void main(String[] args) {
31. new MouseAdapterExample();
32. }
33. }
Output: