Professional Documents
Culture Documents
Java Uses the Delegation Event Model to handle the events. The Delegation Event Model has the
following :
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to an
event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received , the listener process the event an then returns.
2. Event Sources
A source is an object that generates an occasion. This occurs when the interior state of that object
changes. Sources may generate quite one sort of event. A source must register listeners so as for
the listeners to receive notifications a few specific sorts of events. Each sort of event has its own
registration method. Here is the general form:
Here, the Type is the name of the event and el may be a regard to the event listener.
3. Event Listeners in Java
A listener is an object that’s notified when an occasion occurs. It has two major requirements.
First, it registered with one or more sources to receive notifications about specific sorts of events.
Second, it implements methods to receive and process these notifications. The methods that
receive and process events are defined in interfaces found in java.awt.event.
8. MouseEvent MouseListener and mouseClicked(), A mouse event occurs when the user
mousePressed(), interacts with the mouse.
mouseEntered(),
mouseExited() and
mouseReleased()
mouseDregged() and
MouseMotionListene mouseMoved()
r
ActionListener Interface:
The ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method:
1. actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
Example
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}
Output:
ItemEvent and ItemListener :
ItemEvent :
An instance of the ItemEvent class is passed to the ItemListener whenever the item selected in a
list control (such as a list box or combo box) is changed. You can use this object to determine
information about the event such as which item the user selected.
ItemListener :
The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method:
1. itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.
Example
import java.awt.*;
import java.awt.event.*;
public class AwtItemEvent extends Frame{
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea);
Choice choice = new Choice();
choice.addItem("Java");
choice.addItem("Oracle");
choice.addItem("MySQL");
choice.addItem("Python");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("You have selected " + e.getItem() );
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice);
setSize(400,400);
setVisible(true);
setResizable(false);
}
KeyListener:
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
Example:
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener {
Label l;
TextArea area;
KeyListenerExample() {
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output:
MouseListener:
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
TextEvent,
The object of this class represents the text events.The TextEvent is generated when character is
entered in the text fields or text area. The TextEvent instance does not include the characters
currently in the text component that generated the event rather we are provided with other
methods to retrieve that information.
TextListener interface allows to react to changes the text contained in components of type
TextField and TextArea. The addTextListener () method enables a text component to generate
user events. the method TextValueChanged () receives events.
Its interface requires that the method be implemented textValueChanged whose associated
event, java.awt.event.TextEvent, has a specific method interest listed below:
import java.awt.*;
import java.awt.event.*;
class JavaExampleTextEvent extends Frame implements TextListener
{
TextField Txt;
public JavaExampleTextEvent()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Example of Text Listener");
setLayout(new FlowLayout());
Txt=new TextField(20);
Txt.addTextListener(this);
add(Txt);
setSize(400,400);
setVisible(true);
}
public void textValueChanged(TextEvent Evnt)
{
setTitle(Txt.getText());
}
public static void main(String aa[])
{
new JavaExampleTextEvent();
}
}
WindowEvent,
A low-level event that indicates that a window has changed its status. This low-level event is
generated by a Window object when it is opened, closed, activated, deactivated, iconified, or
deiconified, or when focus is transfered into or out of the Window.
The event is passed to every WindowListener or WindowAdapter object which registered to
receive such events using the window's addWindowListener method. (WindowAdapter objects
implement the WindowListener interface.) Each such listener object gets
this WindowEvent when the event occurs.
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class WindowExample extends Frame implements WindowListener {
WindowExample() {
addWindowListener(this);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public static void main(String[] args) {
new WindowExample();
}
prints the given string when window is set to be active
public void windowActivated (WindowEvent arg0) {
System.out.println("activated");
}
public void windowClosed (WindowEvent arg0) {
System.out.println("closed");
}
public void windowClosing (WindowEvent arg0) {
System.out.println("closing");
dispose();
}
public void windowDeactivated (WindowEvent arg0) {
System.out.println("deactivated");
}
public void windowDeiconified (WindowEvent arg0) {
System.out.println("deiconified");
}
public void windowIconified(WindowEvent arg0) {
System.out.println("iconified");
}
public void windowOpened(WindowEvent arg0) {
System.out.println("opened");
} }
Class constructors
S.N. Constructor & Description
Component getComponent()
1
Returns the originator of the event.
String paramString()
2
Returns a parameter string identifying this event.
AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)
Constructs an AdjustmentEvent object with the specified Adjustable source, event type,
adjustment type, and value.
Class methods
S.N. Method & Description
Adjustable getAdjustable()
1
Returns the Adjustable object where this event originated.
2 int getAdjustmentType()
Returns the type of adjustment which caused the value changed event.
int getValue()
3
Returns the current value in the adjustment event.
boolean getValueIsAdjusting()
4
Returns true if this is one of multiple adjustment events.
String paramString()
5
Returns a string representing the state of this Event.
Introduction 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.
Sr.
Control & Description
No.
Label
1
A Label object is a component for placing text in a container.
Button
2
This class creates a labeled button.
Check Box
3
A check box is a graphical component that can be in either an on (true) or off (false) state.
List
5
The List component presents the user with a scrolling list of text items.
Text Field
6
A TextField object is a text component that allows for the editing of a single line of text.
Text Area
7
A TextArea object is a text component that allows for the editing of a multiple lines of text.
Choice
8 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.
Image
10
An Image control is superclass for all image classes representing graphical images.
Scroll Bar
11 A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
Dialog
12 A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
File Dialog
13
A FileDialog control represents a dialog window from which the user can select a file.
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
import java.awt.*;
// main method
public static void main(String args[])
{
new ListExample1();
}
}
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:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
FileName: FlowLayoutExample.java
import java.awt.*;
import javax.swing.*;
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
Example of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
FileName: GridLayoutExample.java
import java.awt.*;
import javax.swing.*;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Introduction to I/O Streams
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.
In 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
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 is used to write an array of byte to the current output
IOException 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
IOException at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException from the current input stream.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
To write a byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
To write a string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}