You are on page 1of 28

UNIT – V

Introduction to Event Handling


Events are generated as result of user interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs.

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.

Components of Event Handling


1. Events
An event is an object that describes a phase change during a source. It is often generated as a
consequence of an individual interacting with the graphical interface. Some activities that cause
events to be generated are pressing a button, entering a data via the keyboard, selecting an item
during in a list, and clicking the mouse. Events can also occur that aren’t directly caused by
interactions with an interface. For example, an occasion could also be generated when a timer
expires, a counter exceeds a worth, a software or hardware failure occurs, or an operation is
completed.

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:

public void addTypeListener(TypeListener el)

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.

Steps to Handle Event in Java


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event generation,
and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

S. Event Class Listener Interface Methods Descriptions


No.

1. ActionEvent ActionListener actionPerformed() ActionEvent indicates that a


component-defined action occurred.

2. AdjustmentEv AdjustmentListener adjustmentValueCha Adjustment events occur by an


ent nged() adjustable object like a scrollbar.

3. ComponentEv ComponentListener componentResized(), An event occurs when a component


ent componentMoved(), moved, changed its visibility or the size
componentShown() changed.
and
componentHidden()
4. ContainerEven ContainerListener componentRemoved( The event is fired when a component is
t ) and added or removed from a container.
componentAdded()

5. FocusEvent FocusListener focusLost() and Focus events include focus, focusout,


focusGained() focusin, and blur.

6. ItemEvent ItemListener itemStateChanged() Item event occurs when an item is


selected.

7. KeyEvent KeyListener keyPressed(), A key event occurs when the user


keyReleased(), and presses a key on the keyboard.
keyTyped().

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

9. MouseWheelE MouseWheelListener mouseWheelMoved() MouseWheelEvent occurs when the


vent . mouse wheel rotates in a component.

10. TextEvent TextListener textChanged() TextEvent occurs when an object's text


change.

11. WindowEvent WindowListener windowActivated(), Window events occur when a window's


windowDeactivated() status is changed.
windowOpened(),
windowClosed(),
windowClosing(),
windowIconfied()
and
windowDeiconified()
.

ActionEvent & ActionListener:


ActionEvent class:
This class is defined in java.awt.event package. The ActionEvent is generated when button is
clicked or the item of a list is double clicked.

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.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener


Implement the ActionListener.

To implement the ActionListener class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:


public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}

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.

public abstract void itemStateChanged(ItemEvent e);

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);
}

public static void main(String[] args){


AwtItemEvent f = new AwtItemEvent("CheckBoxDemo");
}
}

KeyEvent and KeyListener:


KeyEvent:
A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED. The first two events are generated when any key is pressed or released.
The last event occurs only when a character is generated. Remember, not all keypresses result in
characters. For example, pressing shift does not generate a character.

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:

1. public interface KeyListener extends EventListener

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:

MouseEvent and MouseListener:


An event which indicates that a mouse action occurred in a component. A mouse action is
considered to occur in a particular component if and only if the mouse cursor is over the
unobscured part of the component's bounds when the action happens. A mouse event type is
enabled by adding the appropriate mouse-based EventListener to the component
(MouseListener or MouseMotionListener.
.
This low-level event is generated by a component object for:
 Mouse Events
 a mouse button is pressed
 a mouse button is released
 a mouse button is clicked (pressed and released)
 the mouse cursor enters the unobscured part of component's geometry
 the mouse cursor exits the unobscured part of component's geometry
 Mouse Motion Events
 the mouse is moved
 the mouse is dragged

A MouseEvent object is passed to every MouseListener or MouseAdapter object which is


registered to receive the "interesting" mouse events using the
component's addMouseListener method. (MouseAdapter objects implement
the MouseListener interface.)

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:

toString() - Returns the string associated with the event.

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.

public interface WindowListener extends EventListener

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");
} }

ComponentEvent and ComponentListener


A low-level event which indicates that a component moved, changed size, or changed visibility
(also, the root class for the other component-level events).
Component events are provided for notification purposes ONLY; The AWT will automatically
handle component moves and resizes internally so that GUI layout works properly regardless of
whether a program is receiving these events or not.
In addition to serving as the base class for other component-related events (InputEvent,
FocusEvent, WindowEvent, ContainerEvent), this class defines the events that indicate changes
in a component's size, position, or visibility.
This low-level event is generated by a component object (such as a List) when the component is
moved, resized, rendered invisible, or made visible again. The event is passed to
every ComponentListener or ComponentAdapter object which registered to receive such events
using the component's addComponentListener method. (ComponentAdapter objects implement
the ComponentListener interface.) Each such listener object gets this ComponentEvent when the
event occurs.

Class constructors
S.N. Constructor & Description

ComponentEvent(Component source, int id)


1
Constructs a ComponentEvent object.
Class methods
S.N. Method & Description

Component getComponent()
1
Returns the originator of the event.

String paramString()
2
Returns a parameter string identifying this event.

AdjustmentEvent and AdjustmentListener


The adjustment event emitted by Adjustable objects like Scrollbar and ScrollPane. When the user
changes the value of the scrolling component, it receives an instance of AdjustmentEvent. An
unspecified behavior will be caused if the id parameter of any particular Adjustment
Event instance is not in the range from ADJUSTMENT_FIRST to ADJUSTMENT_LAST.
The type of any AdjustmentEvent instance takes one of the following values:
 UNIT_INCREMENT
 UNIT_DECREMENT
 BLOCK_INCREMENT
 BLOCK_DECREMENT
 TRACK

AdjustmentEvent(Adjustable source, int id, int type, int value)


Constructs an AdjustmentEvent object with the specified Adjustable source, event type,
adjustment type, and value.

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.

Check Box Group


4
The CheckboxGroup class is used to group the set of checkbox.

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.

Working with Label controls

import java.awt.*;
public class LabelExample {
public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Working with Buttons controls

import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Working with CheckBoxes
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}

Working with CheckBoxGroup controls

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();
}
}

Working with Choice controls controls

import java.awt.*;
public class ChoiceExample1 {

// class constructor
ChoiceExample1() {

// creating a frame
Frame f = new Frame();

// creating a choice component


Choice c = new Choice();

// setting the bounds of choice menu


c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");

// adding choice menu to frame


f.add(c);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}

Working with Lists controls

import java.awt.*;

public class ListExample1


{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);
// setting the position of list component
l1.setBounds(100, 100, 75, 75);

// adding list items into the list


l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");

// adding the list to frame


f.add(l1);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ListExample1();
}
}

Working with TextField controls


import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");

// creating objects of textfield


TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Introduction to Layout Manager

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.

Understanding Flow Layout


The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout() constructor

FileName: FlowLayoutExample.java
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample


{

JFrame frameObj;

// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");

// adding the buttons to frame


frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);

// parameter less constructor is used


// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}

// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:

Understanding Border Layout

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.*;

public class Border


{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:

Understanding Grid Layout

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.*;

public class GridLayoutExample


{
JFrame frameObj;

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

// adding buttons to the frame


// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);

// setting the grid layout using the parameterless constructor


frameObj.setLayout(new GridLayout());

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.

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

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


IOException
InputStream Hierarchy
To read single character:

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 read all Characters


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
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);}
}
}

You might also like