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

javapackages notes.doc

Uploaded by

rachalaanirudh27
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)
15 views

javapackages notes.doc

Uploaded by

rachalaanirudh27
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/ 40

What is a Package

 A package is a namespace that organizes a set of related classes and interfaces.


 A Java package is a mechanism for organizing Java classes into namespaces.
 A package is a logical container of classes, interfaces and sub-packages.

Advantages of packages

 Grouping related classes.


 Avoid naming conflicts.
 Provide Access protection

Syntax

package Package_Name;

EX: package P1;

Example

package P1;

public class Test

public static void main(String arr[])

System.out.println(“This is package P1”);

Package compilation: javac –d . Test.java

Execution of package: java P1.Test

Some of packages in java

 java.lang : basic language functionality and fundamental types.


 java.util : collection data structure classes.
 java.io : file operations.
 java.math : multiprecision arithmetics.
 java.nio : the New I/O framework for Java.
 java.net : networking operations, sockets.
 java.security : key generation, encryption and decryption.
 java.sql : Java Database Connectivity (JDBC) to access databases.
 java.awt : basic hierarchy of packages for native GUI components.
 javax.swing : hierarchy of packages for platform-independent rich GUI components.
 java.applet : classes for creating an applet

Types of packages in java

1.Predefined or Built in

2.Userdefined

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*


package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

t is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage
Access specifiers

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Explain about java API packages

Java API
An API stands for Application Programming Interface, and it is an interface that allows
communication between different applications using the packages it comprises. Java API
comprises a collection of interfaces, classes, and packages. It helps us to use the packaged
classes and interfaces to build our applications and supports reusability. Whenever we write
any program in java, we use the Java API to do so. For example, we use JDBC API in java to
connect to any database server to perform several transactions using java.

 java.util : collection data structure classes.


 java.io : file operations.
 java.math : multiprecision arithmetics.
 java.nio : the New I/O framework for Java.
 java.net : networking operations, sockets.
 java.security : key generation, encryption and decryption.
 java.sql : Java Database Connectivity (JDBC) to access databases.
 java.awt : basic hierarchy of packages for native GUI components.
 javax.swing : hierarchy of packages for platform-independent rich GUI components.

java.applet : classes for creating an applet

CLASSPATH: CLASSPATH is an environment variable which is used by Application


ClassLoader to locate and load the .class files. The CLASSPATH defines the path, to find
third-party and user-defined classes that are not extensions or part of Java platform. Include
all the directories which contain .class files and JAR files when setting the CLASSPATH.

Step 1: Click on the Windows button and choose Control Panel. Select System.

Step 2: Click on Advanced System Settings.


Step 3: A dialog box will open. Click on Environment Variables.

Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then
put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and type
Variable name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\
MySQL-Connector Java.jar;.;

Remember: Put ;.; at the end of the CLASSPATH.

Java Stream Class


A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination. InputStream and
OutputStream are the basic stream classes in Java.

Types of streams:

 Byte Stream : It provides a convenient means for handling input and output of
byte.

 Character Stream : It provides a convenient means for handling input and output
of characters. Character stream uses Unicode and therefore can be
internationalized.

1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to an output
stream.

 InputStream Classes - These classes are subclasses of an abstract class,


InputStream and they are used to read bytes from a source(file, memory or
console).

 OutputStream Classes - These classes are subclasses of an abstract class,


OutputStream and they are used to write bytes to a destination(file, memory or
console).
2. Character Stream:
Character stream is also defined by using two abstract classes at the top of the hierarchy, they
are Reader and Writer. These two abstract classes have several concrete classes that handle
Unicode characters.

 Reader classes : Abstract class that define character stream input.

 Writer classes : Abstract class that define character stream output.

Java I/O Tutorial

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

n Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character
Do You Know?

o How to write a common data to multiple files using a single stream only?
o How can we access multiple files by a single stream?
o How can we improve the performance of Input and Output operation?
o How many ways can we read data from the keyboard?
o What does the console class?
o How to compress and uncompress the data of a file?

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure given
below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an


output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream


Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException is used to write an array of byte to the current output stre

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.

Useful methods of InputStream


Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 a
IOException end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException current input stream.

3) public void close()throws is used to close the current input stream.


IOException
InputStream Hierarchy
In Java, an applet

is a special type of program embedded in the web page to generate dynamic content. Applet
is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.

Along with the browser, the applet also works on the client side, thus having less processing
time.

Hierarchy of Applet

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Methods of Applet Life Cycle

There are five methods of an applet life cycle, and they are:

o nit(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab to another in the browser. It is
in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()

Applet Life Cycle Working


o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-
side. It doesn't have the main() method because it runs in the browser. It is thus
created to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet
class. And thus, we can use all the methods of that class.

Flow of Applet Life Cycle:

These methods are invoked by the browser automatically. There is no need to call them
explicitly.
How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

to execute the applet by appletviewer tool, write in command prompt:


1. c:\>javac First.java
2. c:\>appletviewer First.java

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

The java.awt package

provides classes

for AWT API such as TextField

, Label

, TextArea

, RadioButton, CheckBox
, Choice

, List

etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below, all the classes are available
in java.awt package.

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

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.

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 m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default 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)

Creating Frame window by extending Frame class

package testawt;

import java.awt.*;
import java.awt.event.*;

public class Testawt extends Frame


{
public Testawt()
{
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}

public static void main (String[] args)


{
Testawt ta = new Testawt(); //creating a frame.
}
}

Creating Frame Window by Instantiating Frame class

import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
AWT classes
AWT Button

In Java, AWT contains a Button Class. It is used for creating a labelled button which can
perform an action.

AWT Button Classs Declaration:

public class Button extends Component implements Accessible

import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}

AWT Label

In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single
line text is allowed and the text can not be changed directly.
Label Declaration:

public class Label extends Component implements Accessible

Example:

In this example, we are creating two labels to display text to the frame

import java.awt.*;

class LabelDemo1

public static void main(String args[])

Frame l_Frame= new Frame("studytonight ==> Label Demo");

Label lab1,lab2;

lab1=new Label("Welcome to studytonight.com");

lab1.setBounds(50,50,200,30);

lab2=new Label("This Tutorial is of Java");

lab2.setBounds(50,100,200,30);

l_Frame.add(lab1);

l_Frame.add(lab2);

l_Frame.setSize(500,500);

l_Frame.setLayout(null);

l_Frame.setVisible(true);

}
AWT TextField

In Java, AWT contains aTextField Class. It is used for displaying single line text.

TextField Declaration:

public class TextField extends TextComponent

Example:

We are creating two textfields to display single line text string. This text is editable in nature,
see the below example.

import java.awt.*;

class TextFieldDemo1{

public static void main(String args[]){

Frame TextF_f= new Frame("studytonight ==>TextField");

TextField text1,text2;

text1=new TextField("Welcome to studytonight");

text1.setBounds(60,100, 230,40);

text2=new TextField("This tutorial is of Java");

text2.setBounds(60,150, 230,40);

TextF_f.add(text1);

TextF_f.add(text2);
TextF_f.setSize(500,500);

TextF_f.setLayout(null);

TextF_f.setVisible(true);

AWT TextArea

In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.

TextArea Declaration:

public class TextArea extends TextComponent

Example:

In this example, we are creating a TextArea that is used to display multiple-line text string
and allows text editing as well.

public class TextAreaDemo1

TextAreaDemo1()

Frame textArea_f= new Frame();

TextArea area=new TextArea("Welcome to studytonight.com");

area.setBounds(30,40, 200,200);
textArea_f.add(area);

textArea_f.setSize(300,300);

textArea_f.setLayout(null);

textArea_f.setVisible(true);

public static void main(String args[])

new TextAreaDemo1();

AWT Checkbox

In Java, AWT contains a Checkbox Class. It is used when we want to select only one option
i.e true or false. When the checkbox is checked then its state is "on" (true) else it is
"off"(false).

Checkbox Syntax

public class Checkbox extends Component implements ItemSelectable, Accessible

Example:

In this example, we are creating checkbox that are used to get user input. If checkbox is
checked it returns true else returns false.
import java.awt.*;

public class CheckboxDemo1

CheckboxDemo1(){

Frame checkB_f= new Frame("studytonight ==>Checkbox Example");

Checkbox ckbox1 = new Checkbox("Yes", true);

ckbox1.setBounds(100,100, 60,60);

Checkbox ckbox2 = new Checkbox("No");

ckbox2.setBounds(100,150, 60,60);

checkB_f.add(ckbox1);

checkB_f.add(ckbox2);

checkB_f.setSize(400,400);

checkB_f.setLayout(null);

checkB_f.setVisible(true);

public static void main(String args[])

new CheckboxDemo1();

}
AWT CheckboxGroup

In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time.

CheckboxGroup Declaration:

public class CheckboxGroup extends Object implements Serializable

Example:

This example creates a checkboxgroup that is used to group multiple checkbox in a single
unit. It is helpful when we have to select single choice among the multiples.

import java.awt.*;

public class CheckboxGroupDemo

CheckboxGroupDemo(){

Frame ck_groupf= new Frame("studytonight ==>CheckboxGroup");

CheckboxGroupobj = new CheckboxGroup();

Checkbox ckBox1 = new Checkbox("Yes", obj, true);

ckBox1.setBounds(100,100, 50,50);

Checkbox ckBox2 = new Checkbox("No", obj, false);

ckBox2.setBounds(100,150, 50,50);

ck_groupf.add(ckBox1);

ck_groupf.add(ckBox2);

ck_groupf.setSize(400,400);

ck_groupf.setLayout(null);

ck_groupf.setVisible(true);

}
public static void main(String args[])

new CheckboxGroupDemo();

AWT Choice

In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices.
When a user selects a particular item from the drop-down then it is shown on the top of the
menu.

Choice Declaration:

public class Choice extends Component implements ItemSelectable, Accessible

Example:

In this example, we are creating drop-down menu that is used to get user choice from
multiple choices.

import java.awt.*;

public class ChoiceDemo

ChoiceDemo()

{
Frame choice_f= new Frame();

Choice obj=new Choice();

obj.setBounds(80,80, 100,100);

obj.add("Red");

obj.add("Blue");

obj.add("Black");

obj.add("Pink");

obj.add("White");

obj.add("Green");

choice_f.add(obj);

choice_f.setSize(400,400);

choice_f.setLayout(null);

choice_f.setVisible(true);

public static void main(String args[])

new ChoiceDemo();

}
AWT List

In Java, AWT contains a List Class. It is used to represent a list of items together. One or
more than one item can be selected from the list.

List Declaration:

public class List extends Component implements ItemSelectable, Accessible

Example:

In this example, we are creating a list that is used to list out the items.

import java.awt.*;

public class ListDemo

ListDemo()

Frame list_f= new Frame();

List obj=new List(6);

obj.setBounds(80,80, 100,100);

obj.add("Red");

obj.add("Blue");

obj.add("Black");

obj.add("Pink");

obj.add("White");

obj.add("Green");

list_f.add(obj);

list_f.setSize(400,400);

list_f.setLayout(null);
list_f.setVisible(true);

public static void main(String args[])

new ListDemo();

Event Handling in Java


An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement,
keypress through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.

Classification of Events

 Foreground Events
 Background Events

Types of Events

1. Foreground Events
Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows
the Delegation Event model.

Delegation Event model

 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are various
sources like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
 Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible
for handling events.
To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener

Different Classes provide different registration methods.


Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred
like a button click or selecting an item
ActionEvent ActionListener from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener Adjustable object like Scrollbar.

An event that indicates that a


component moved, the size changed
ComponentEvent ComponentListener or changed its visibility.

When a component is added to a


container (or) removed from it, then
this event is generated by a container
ContainerEvent ContainerListener object.

These are focus-related events, which


include focus, focusin, focusout, and
FocusEvent FocusListener blur.

An event that indicates whether an


ItemEvent ItemListener item was selected or not.

An event that occurs due to a


sequence of keypresses on the
KeyEvent KeyListener keyboard.

The events that occur due to the user


MouseListener & interaction with the mouse (Pointing
MouseEvent MouseMotionListener Device).

MouseWheelEvent MouseWheelListener An event that specifies that the mouse


Event Class Listener Interface Description

wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener text changes.

An event which indicates whether a


WindowEvent WindowListener window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented


by the registered class to handle events.
Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener
 actionPerformed()

AdjustmentListener
 adjustmentValueChanged()

 componentResized()
 componentShown()
 componentMoved()
ComponentListener
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener
 itemStateChanged()

 keyTyped()
 keyPressed()
KeyListener
 keyReleased()
Listener Interface Methods

 mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
MouseListener
 mouseReleased()

MouseMotionListene  mouseMoved()
r
 mouseDragged()

// Java program to demonstrate the

// event handling within the class

import java.awt.*;

import java.awt.event.*;

class GFG extends Frame implements ActionListener {

TextField textField;

GFGTop()

// Component Creation

textField = new TextField();

// setBounds method is used to provide

// position and size of the component

textField.setBounds(60, 50, 180, 25);


Button button = new Button("click Here");

button.setBounds(100, 120, 80, 30);

// Registering component with listener

// this refers to current instance

button.addActionListener(this);

// add Components

add(textField);

add(button);

// set visibility

setVisible(true);

// implementing method of actionListener

public void actionPerformed(ActionEvent e)

// Setting text to field

textField.setText("GFG!");

public static void main(String[] args)

new GFGTop();
}

Keyboard Events in Java


It is a subclass of the abstract InputEvent class and is generated when the user
presses or releases a key or does both i.e. types a character.
When a key is pressed, the event generated is KEY_PRESSED
When a key is released, the event generated is KEY_RELEASED
When a character is typed on the keyboard, that is a key is pressed and then
released, the event generated is KEY_TYPED
Following are the types of methods provided by KeyEvent class
int getKeyCode() It is used for getting the integer code associated with a key. It is
used for KEY_PRESSED and KEY_RELEASED events. The keycodes are defined
as constants in KeyEvent class
char getKeyChar() This method is used to get the Unicode character of the key
pressed. It works with the KEY_TYPED events
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="KeyboardEvents.class" WIDTH=300 HEIGHT=200>
</APPLET> */
public class KeyboardEvents extends Applet implements KeyListener
{
TextArea tpress,trel;
TextField t;
public void init()
{
t=new TextField(20);
t.addKeyListener(this);
tpress=new TextArea(3,70);
tpress.setEditable(false);
trel=new TextArea(3,70);
trel.setEditable(false);
add(t);
add(tpress);
add(trel);
}
public void keyTyped(KeyEvent e)
{
disppress(e,"Key Typed:");
}
public void keyPressed(KeyEvent e)
{
disppress(e,"KeyPressed:");
}
public void keyReleased(KeyEvent e)
{
String charString,keyCodeString,modString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
charString="Key character='"+c+"'";
keyCodeString="key
code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
modString="modifiers="+modifiers;
trel.setText("Key released"+charString+keyCodeString+modString);

}
protected void disppress(KeyEvent e,String s)
{
String charString,keyCodeString,modString,tmpString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
if(Character.isISOControl(c))
{
charString="key character=(an unprintable control
character)";
}
else
{
charString="key character='"+c+"'";
}
modString="modifiers="+modifiers;

tmpString=KeyEvent.getKeyModifiersText(modifiers);

if(tmpString.length()>0)
{
modString+="("+tmpString+")";
}
else
{
modString+="(no modifiers)";
}
keyCodeString="key
code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";

tpress.setText(s+charString+keyCodeString+modString);
}
}

You might also like