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

Unit 4 JAVA

New java

Uploaded by

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

Unit 4 JAVA

New java

Uploaded by

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

Dr.

Tejinder Kaur (Associate Professor)

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.

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.

Why AWT is Platform Independent?


The Java AWT utilizes the native platform subroutine to create API components such as TextField, CheckBox,
and buttons. This results in a different visual format for these components on different platforms such as
Windows, MAC OS, and Unix. The reason for this is that each platform has a distinct view of its native
components. AWT directly calls this native subroutine to create the components, resulting in an AWT
application resembling a Windows application on Windows OS, and a Mac application on the MAC OS. In
simpler terms, the AWT application’s appearance adapts to the platform it is running on.
AWT is platform independent even after the AWT components are platform dependent because of the points
mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract API which are
platform independent. Abstract API allows Java to isolate platform-specific details, making code portable across
different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent. Because of this, it
ensures that AWT functionality remains consistent across different environments.
Java AWT Hierarchy
Dr.Tejinder Kaur (Associate Professor)

 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 AWT Choice:


public class Choice extends Component implements ItemSelectable, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
8. Java AWT Canvas
Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
Java AWT Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1. Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2. Scrollbar(int orientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the default value and [mini, maxi] as the
lower and higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows you to create
individual items that can be added to menus. And Menu is a component used to create a dropdown menu that
can contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up a menu that appears when the
user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible
12. Java AWT Panel
Java AWT Panel is a container class used to hold and organize graphical components in a Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
13. Java AWT Toolkit
Java AWT Toolkit class provides us with a platform-independent way to access various system resources and
functionalities. Subclasses of Toolkit are used to bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object
Event Handling Components – Java AWT
Dr.Tejinder Kaur (Associate Professor)

Here are some of the event handling components in Java:


 Java ActionListener
 Java MouseListener
 Java MouseMotionListener
 Java ItemListener
 Java KeyListener
 Java WindowListener
 Close AWT Window
1. Java ActionListener
Java ActionListner is a interface which responds to the actions performed by the components like buttons, menu
items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener
There is only methods associated with ActionListner class that is actionPerformed().
Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);
2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by mouse events generated by the user.
Example: mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a component’s bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.
4. Java ItemListener
Java ItemListner is an interface which handles events related to item selection and deselection those that occur
with checkboxes, radio buttons, etc. There is only one Method associated with ItemListner that is
itemStateChanged(). This method provides information about the event, i.e. source of the event and the changed
state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)
5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state of key or can be said for key
related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window actions. Events like opening ,
closing, minimizing, etc are handled using WindowListener.
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

// Java AWT Program for Hello World


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// 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!");

// Aligning the label to CENTER


label.setAlignment(Label.CENTER);

// Adding Label and Setting


// the Size of the Frame
frame.add(label);
frame.setSize(300, 300);

// Making the Frame visible


frame.setVisible(true);
Dr.Tejinder Kaur (Associate Professor)

// Using WindowListener for closing the window


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

Working with Frame Windows in Java

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.

Setting the Windows Dimensions

The setSize( ) method is used to set the dimensions of the window. Its signature is shown below:

i. void setSize(int newWidth, int newHeight) void setSize(Dimension newSize)

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.

ii. Hiding and showing a Window

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.

iii. Setting a Windows Title

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.

iv.Closing a Frame Window


Dr.Tejinder Kaur (Associate Professor)

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

Every user interface considers the following three main aspects:

 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.

4 Check Box Group


The CheckboxGroup class is used to group the set of checkbox.
Dr.Tejinder Kaur (Associate Professor)

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.

Designing menus and dialog boxes.

Java AWT Dialog

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.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't
have.

AWT Dialog class declaration

1. public class Dialog extends Window

Delegation Event Model in Java

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.

Event Processing in Java

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.

Basically, an Event Model is based on the following three components:

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:

1. public void addTypeListener (TypeListener e1)

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.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException

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.

1. public void removeTypeListener(TypeListener e2?)

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 events are categories into the following two categories:

The Foreground Events:


Dr.Tejinder Kaur (Associate Professor)

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 :

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

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

The design goals of the event delegation model are as following:

o It is easy to learn and implement

o It supports a clean separation between application and GUI code.

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.

Let's implement it with an example:

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)

49. Command searchCmd = new Command(Command.SEARCH, app);


50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }

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.

VB.Net is an event-driven language. There are mainly two types of events −

 Mouse events
 Keyboard events
Dr.Tejinder Kaur (Associate Professor)

Handling Mouse Events

Mouse events occur with mouse movements in forms and controls. Following are the various mouse events
related with a Control class −

 MouseDown − it occurs when a mouse button is pressed


 MouseEnter − it occurs when the mouse pointer enters the control
 MouseHover − it occurs when the mouse pointer hovers over the control
 MouseLeave − it occurs when the mouse pointer leaves the control
 MouseMove − it occurs when the mouse pointer moves over the control
 MouseUp − it occurs when the mouse pointer is over the control and the mouse button is released
 MouseWheel − it occurs when the mouse wheel moves and the control has focus

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 −

 Buttons − indicates the mouse button pressed


 Clicks − indicates the number of clicks
 Delta − indicates the number of detents the mouse wheel rotated
 X − indicates the x-coordinate of mouse click
 Y − indicates the y-coordinate of mouse click

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

Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_


Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _


Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub

Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _


Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub
Dr.Tejinder Kaur (Associate Professor)

Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _


Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _


Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _


Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class

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)

Handling Keyboard Events

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 −

 Alt − it indicates whether the ALT key is pressed


 Control − it indicates whether the CTRL key is pressed
 Handled − it indicates whether the event is handled
 KeyCode − stores the keyboard code for the event
 KeyData − stores the keyboard data for the event
 KeyValue − stores the keyboard value for the event
 Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
 Shift − it indicates if the Shift key is pressed

The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs. This object has
the following properties −

 Handled − indicates if the KeyPress event is handled


 KeyChar − stores the character corresponding to the key pressed

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)

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
 Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
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 −

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

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:

o It assists the unrelated classes to work combinedly.

o It provides ways to use classes in different ways.

o It increases the transparency of classes.

o It provides a way to include related patterns in the class.

o It provides a pluggable kit for developing an application.

o 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


Dr.Tejinder Kaur (Associate Professor)

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd 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


Dr.Tejinder Kaur (Associate Professor)

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:
Dr.Tejinder Kaur (Associate Professor)

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.
5. // class which inherits the MouseAdapter class
6. public class MouseAdapterExample extends MouseAdapter {
7. // object of Frame class
8. Frame f;
9. // class constructor
10. MouseAdapterExample() {
11. // creating the frame with the title
12. f = new Frame ("Mouse Adapter");
13. // adding MouseListener to the Frame
14. f.addMouseListener(this);
15. // setting the size, layout and visibility of the frame
16. f.setSize (300, 300);
17. f.setLayout (null);
18. f.setVisible (true);
19. }
20. // overriding the mouseClicked() method of the MouseAdapter class
21. public void mouseClicked (MouseEvent e) {
Dr.Tejinder Kaur (Associate Professor)

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:

You might also like