Unit 5 Notes Java-New Syllabus
Unit 5 Notes Java-New Syllabus
1.Input/output Streams
1.1) File:
File is a collection of information (data) stored on a computer. A file is a section of
storage, usually on a disk. The operating system sees a file as a complicated entity with data
segments and pointers scattered all over the disk. Each file has a name and a file extension,
indicating the kind of data it contains or the software used to create it.
By using a file as a source of input data, you can prepare the data before running a
program, and the program can access the data each time it runs. Saving output to a file
allows the output to be saved and distributed to others, and the output produced by one
program can be used as input to other programs.
Files that consist of a sequence of binary digits are called binary files. Binary files are
designed to be read on the same type of computer and with the same programming language
as the computer that created the file. An advantage of binary files is that they are more
efficient to process than text files.
Constructors:
File(String path)
File file= new File("D:\\Textbook.txt");
Methods of File class:
2 Unit 5 Notes – Java Programming
Example:
import java.io.*;
class A
{
public static void main(String args[])
{
File f= new File("D:\\TextBook1.txt");
System.out.println("Does this file exists? "+f.exists());
System.out.println("The name of file is "+f.getName());
System.out.println("Parent Directory of this file "+f.getParent());
System.out.println("Path to this file "+f.getPath());
System.out.println("The full path to this file "+f.getAbsolutePath());
System.out.println("Is this a Directory? "+f.isDirectory());
System.out.println("Is this a File? "+f.isFile());
System.out.println("Is this a hidden file "+f.isHidden());
System.out.println("Is this File readable ? "+f.canRead());
System.out.println("Is this File writable ? "+f.canWrite());
}
}
Output:
Does this file exists? false
The name of file is TextBook1.txt
Parent Directory of this file D:\
Path to this file D:\TextBook1.txt
The full path to this file D:\TextBook1.txt
Is this a Directory? false
Is this a File? false
Is this a hidden file false
Is this File readable ? false
Is this File writable ? false
1.2) 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, three 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
3 Unit 5 Notes – Java Programming
• An InputStream represents a stream of data from which data can be read. Again, this
stream will be either directly connected to a device or else to another stream.
• An OutputStream represents a stream to which data can be written. Typically, this
stream will either be directly connected to a device, such as a file or a network
connection, or to another output stream.
The super class InputStream is an abstract class, and, therefore, we cannot create
instances of this class. Rather, we must use the subclasses that inherit from this class.
InputStream class defines the methods to perform the following functions: -
▪ Reading Bytes
▪ Closing Streams
5 Unit 5 Notes – Java Programming
▪ Marking position in Streams
▪ Skipping ahead in streams
▪ Finding the number of bytes in stream.
Methods:
The super class Output stream is an abstract class, so we cannot create object for
the class. Output stream class defines the methods to perform the following functions:
▪ Writing Bytes
▪ Closing Streams
▪ Flushing Streams
6 Unit 5 Notes – Java Programming
Methods:
2.Applet
2.1) Applet:
Applet is a tiny Java program used in Internet computing. These Programs can be
transported over the internet from one system to another and run using AppletViewer or any
web browser that supports Java. They are similar to application programs. They can perform
arithmetic operations, display graphics, play sounds and so on.
2.2) Local and remote applets:
Applets can be embedded into web pages in two ways namely:
1. Local Applet
2. Remote Applet
1.Local applets:
We can create our own applets and embed them into web pages. An applet which is
developed locally and stored in a local system is known as local applet. When a web page
tries to find a local applet, it does not need to use the internet and hence does not require
internet connection. It simply searches the directories in the local system and locates and
loads the specified applet. Fig.8.1 shows how local applets can be loaded.
2.Remote applets:
An applet can be downloaded from a remote system and then it can be embedded into
a web page. Such an applet is called a Remote applet. A remote applet is developed by
someone else and stored in a remote computer system connected to the Internet. Our system
has to be connected to the Internet to download this remote applet into our system using the
Internet connection between the remote system and our system. To download a remote applet
the address of the applet should be known. This address is called the URL (Uniform
9 Unit 5 Notes – Java Programming
Resource Locator). This URL is used as the CODEBASE attribute of the applet's HTML
document.
Example: CODEBASE = http://www.netserve.com/applets
2. Running State:
Applet enters the running state when the system calls the start() method of Applet
class. This occurs automatically after the applet is initialized. An applet may also start when
it is in idle state. At that time, the start () method is overridden. Its general form is:
public void start()
{
.............
.............
(Action)
}
3. Idle State:
An applet comes in idle state when its execution has been stopped either implicitly or
explicitly. An applet is implicitly stopped when we leave the page containing the currently
running applet. An applet is explicitly stopped when we call the stop () method to stop its
execution. Its general form is:
public void stop()
{
.............
.............
(Action)
}
11 Unit 5 Notes – Java Programming
4. Dead State:
An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy () method when we want to quit the browser.
Destroying stage occurs only once in the applet’s life cycle. Its general form is:
public void destroy()
{
.............
.............
(Action)
}
5.Display state:
Applet moves to the display state whenever it has to perform some output operations
on the screen. This happens immediately after the applet enters into the running state. The
paint() method is called to accomplish this task. Almost every applet will have a paint()
method. Its general form is:
public void paint(Graphics g)
{
.............
.............
(Display statements)
}
First create an applet and compile it just like a simple java program.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“Welcome to Applet",50,150);
}
}
<html>
<body>
<applet code="First.class" width="300" height="300"> </applet>
</body>
</html>
import java.applet.Applet;
import java.awt.;
/* <applet code="First.class" width="300" height="300"> </applet> */
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",50,150);
}
}
Explanation:
Param Tag:
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value
of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:
Now, these two parameters can be accessed in the applet program using the getParameter()
method of the Applet class.
Syntax:
The getParameter() method of the Applet class can be used to retrieve the parameters
15 Unit 5 Notes – Java Programming
passed from the HTML page.
Let’s look at a sample program which demonstrates the <param> HTML tag and the
getParameter() method:
import java.awt.*;
import java.applet.*;
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
Output :
16 Unit 5 Notes – Java Programming
2.8) Aligning the display:
The align attribute specifies the alignment of an <object> element according to the
surrounding element. The <object> element is an inline element (it does not insert a new line
on a page), meaning that text and other elements can wrap around it. Therefore, it can be
useful to specify the alignment of the <object> according to surrounding elements.
Syntax
<object align="left|right|middle|top|bottom">
Attribute Values:
3. Graphics Class
3.1 Graphics Class:
The graphics class defines several drawing methods. All graphics are drawn relative to
window. The origin of each window is top left corner and is 0,0. The co-ordinates are
specified in pixels. The co-ordinate position (20, 50) points the column number 20 and
row number 50. The graphics context is encapsulated by the following two methods.
Syntax:
Example:
_______
public void paint(Graphics g)
{
g.drawLine(30,20, 200,300);
______
}
17 Unit 5 Notes – Java Programming
3.1.2 Drawing Rectangles:
The methods used to draw a rectangle and fill the rectangle are given below.
Syntax:
Here top and left indicates the top-left corner of the rectangle, the length represents the
length of a rectangle and breadth represents the breadth of a rectangle. The fillRect( )
method is used to fill the rectangle.
Example:
________
public void paint(Graphics g)
{
g.drawRect(100,100, 200,300);
g.fillRect(100,100, 200,300);
______
}
Syntax:
Example:
________
public void paint(Graphics g)
{
g.drawOval(100,100, 200,300); //Ellipse
g.fillOval(100,100, 200,300); //Ellipse
g.drawOval(150,150, 50,50); //Circle
g.fillOval(150,150, 50,50); //Circle
______
}
18 Unit 5 Notes – Java Programming
3.1.4 Drawing arcs and fillarcs:
Java also has methods to draw outlined and filled arcs. They're similar to drawOval()
and fillOval() but you must also specify a starting and ending angle for the arc. Angles are
given in degrees. The arc is drawn conterclockwise if sweepAngle is positive, and clockwise
if sweetAngle is negative.
Syntax:
void drawArc(int left, int top, int width, int height, int startangle, int stopangle)
void fillArc(int left, int top, int width, int height, int startangle, int stopangle)
The rectangle is filled with an arc of the largest circle that could be enclosed within it. The
arc is drawn clockwise or counter-clockwise are currently platform dependent.
Polygons are shapes with many sides. A polygon may be considered as set of lines connected
together.
Syntax:
xpoints is an array that contains the x coordinates of the polygon. ypoints is an array that
contains the y coordinates. Both should have the length npoints. Thus, to construct a 3-4-5
right triangle initialise as follows:
int[] xpoints = {0, 3, 0};
int[] ypoints = {0, 0, 4};
Example:
______
public void paint(Graphics g)
{
g.drawPolygon(xpoints, ypoints, 3);
g.fillPolygon(xpoints, ypoints, 3);
}
Java automatically closes the polygons it draws.
19 Unit 5 Notes – Java Programming
3.1.4 Java program to demonstrate the Graphics methods.
import java.applet.*;
import java.awt.*;
<applet code="Graphics.class" width="300" height="300"> </applet>
public class Graphics extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
}
}
Output:
The variation of Y, when X is increased can be shown graphically using the program. The
graph is drawn in an area 400x400 pixels. The table below shows the new values of X and Y.
20 Unit 5 Notes – Java Programming
Example:
import java.awt.*;
import java.applet.*;
/*<applet code = "Line_Graph.class" width = "640" height = "480"></applet>*/
public class Line_Graph extends Applet
{
int x[]={ 0, 60, 120, 180, 240, 300, 360, 400};
int y[]={ 400, 280, 220, 140, 60, 60, 100, 220};
int z=x.length;
public void paint(Graphics g)
{
g.drawPolygon(x, y, z);
}
}
Example:
import java.awt.*;
import java.applet.*;
setBackground(Color.pink);
try {
int n = Integer.parseInt(getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getParameter("label4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] = Integer.parseInt(getParameter("c2"));
value[2] = Integer.parseInt(getParameter("c3"));
value[3] = Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++) {
g.setColor(Color.black);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.red);
g.fillRect(50,i*50+10,value[i],40);
}
}
}
22 Unit 5 Notes – Java Programming
Methods:
• void setText(String name); // Used to change the existing text or to set text for a
label.
• String getText( ); // Returns the name of the current label.
• void setAlignment(int pos); // used to set alignment of the name within label .
• int getAlignment( ); // Returns the position/alignment of the current label.
4.3.2 Button:
A Button is a component that contains a label. Button is the most commonly used control. It
generates an event when it is pressed.
25 Unit 5 Notes – Java Programming
Constructors:
• Button( ); // Default constructor to create a button.
• Button( String name); // Creates a button with its name.
Methods:
• void setLabel(String name ) ; // Used to set/change the button name.
• String getLabel( ); // Returns the name of the button.
Example for Buttons:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="ButtonTest" width=200 height=100> </applet>* /
public class ButtonTest extends Applet
{
public void init()
{
Button button = new Button ("OK");
add (button);
}
}
4.3.3 Checkbox:
The Checkbox is a AWT control that is used to ON or OFF (select or deselect) an
option. Checkbox is a small box with check mark if it is in ON state otherwise no check
mark on it. We can add a label to the checkbox to show its purpose. The state of the check
box is changed by clicking on it.
Constructors:
• Checkbox( ); // Default constructor to create a check box
• Checkbox(String name); // Creates a Check box control with the name
• Checkbox(String name, boolean on); // Creates a check box with the name and
is set to ON state
• Checkbox(String name, Boolean on, CheckboxGroup cbgp); // Creates a check
box with the name with ON state and is added to the check box group cbgp.
26 Unit 5 Notes – Java Programming
Methods:
• void setState( Boolean on);// Used to set the state of a Checkbox control.
• boolean getState( ); // Returns the current state of the Checkbox
• void setLabel( String label);// Used to set the label for the Checkbox
• String getLabel( ); // Returns the label of the check box control.
Example for Check Boxes:-
import java.awt.*;
import java.applet.Applet;
/*<applet code="CheckboxTest" width=200 height=100> </applet>*/
public class CheckboxTest extends Applet
{
public void init()
{
Checkbox m = new Checkbox ("Allow Mixed Case");
add (m);
}
}
4.3.5 TextField:
A single line text entry in java is implemented through TextField class. It is also called edit
control. TextField is a sub class of TextComponent. The constructors and methods of
TextField class are given below.
Constructor:
• TextField( ); //Default constructor to create a TextField
• TextField(int characters);// Creates a TextField with a specified number of
• character width.
• TextField(String name);// Creates a TextField with a string name.
Methods:
• String getText( );// Returns the current string in the TextField.
• void setText(String name); //Used to set the text in the name.
• void select(int start, int end);//Used to select the characters in a TextField
• beginning at start and ending at end.
• String getSelectedText( );// Returns the selected text in the TextField.
4.3.6 TextArea:
In java, TextArea provides a multi-line text editor. TextArea is a sub class of Text
Component.
Constructors:
• TextArea( ); //Default constructor to create a TextArea
• TextArea(int lines, int characters); // Creates a TextArea with a specified
number of lines and each line is of characters width.
• TextArea(String name); // Creates a TextArea with a initial string name.
• TextArea(String name, int lines, int characters); // Creates a TextArea with
a initial text name and specified number of lines and each line is of
characters width.
Methods:
• void append( String msg); //Used to append the string specified in the msg.
• void insert(String msg, int location); //Used to insert the string msg in the specified
location.
• void replaceRange(String msg, int start, int end); // Used to replace the existing string
with the new string msg in the specified starting index start and the ending index end.
4.3.7 Scrollbar:-
Scrollbar is represented by a "slider" widget. The characteristics of it are specified by
integer values which are being set at the time of scrollbar construction. Both the types of
Sliders are available i.e. horizontal and vertical.
import java.awt.*;
import java.applet.Applet;
/*<applet code="ScrollbarDemo" width=200 height=100> </applet>*/
public class ScrollbarDemo extends Applet
{
public void init()
{
Scrollbar sb = new Scrollbar (Scrollbar.VERTICAL, 0, 8, -100, 100);
add(sb);
}
}
5. Event Handling
5.1 Event:
Change in the state of an object is known as event i.e. event describes the change in
state of source. 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
30 Unit 5 Notes – Java Programming
character through keyboard, selecting an item from list, scrolling the page are the activities
that causes an event to happen.
5.2 Event Handling:
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism has 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. This model defines the standard mechanism to generate and handle the events.
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
2. AdjustmentEvent:
The adjustment event is generated when the scroll bar is adjusted. There are five types
of adjustment events. For each type there is a constant declared in the class which are as
31 Unit 5 Notes – Java Programming
follows:
BLOCK_DECREMENT
BLOCK_INCREMENT
TRACK
UNIT_DECREMENT
UNIT_INCREMENT
Methods:
• Adjustable getAdjustable() – Returns the object that generated the event.
• int getAdjustmentType() – Returns one of the five constants that represents the type of
event.
• int getValue() – Returns a number that represents the amount of adjustment.
3. ComponentEvent:
A component event is generated when the visibility, position and size of a component
is changed. There are four types of component events which are identified by the following
constants:
COMPONENT_HIDDEN
COMPONENT_SHOWN
COMPONENT_MOVED
COMPONENT_RESIZED
Methods:
• Component getComponent() – Returns the component that generated the event.
4. ContainerEvent:
A container event is generated when a component is added to or removed from the
container. There are two types of container events which are represented by the following
constants:
COMPONENT_ADDED
COMPONENT_REMOVED
Methods:
• Container getContainer() – Returns the reference of the container that generated the
event.
• Component getChild() – Returns the reference of the component that is added to or
removed from the container.
5. FocusEvent :
A focus event is generated when a component gains or loses input focus. These events
are identified by the following constants:
32 Unit 5 Notes – Java Programming
FOCUS_GAINED
FOCUS_LOST
Methods:
• Component getOppositeComponent() – Returns the other component that gained or
lost focus.
• boolean isTemporary() – Method returns true or false that indicates whether the
change in focus is temporary or not.
6. ItemEvent:
An item event is generated when the user clicks on a check box or clicks a list item or
selects / deselects a checkable menu item. These events are identified by the following
constants:
SELECTED
DESELECTED
Methods:
• Object getItem() – Returns a reference to the item whose state has changed.
• ItemSelectable getItemSelectable() – Returns the reference of ItemSelectable object
that raised the event.
• int getStateChange() – Returns the status of the state (whether SELECTED or
DESELECTED)
7. KeyEvent :
A key event is generated when a key on the keyboard is pressed, released or typed.
These events are identified by the following constants:
KEY_PRESSED (when a key is pressed)
KEY_RELEASED (when a key is released)
KEY_TYPED (when a character is typed)
Methods:
• char getKeyChar() – Returns the character entered from the keyboard
• int getKeyCode() – Returns the key code
8. MouseEvent:
The mouse event is generated when the user generates a mouse event on a source.
Mouse events are represented by the following constants:
33 Unit 5 Notes – Java Programming
Methods:
• int getX() – Returns the x-coordinate of the mouse at which the event was generated.
• int getY() – Returns the y-coordinate of the mouse at which the event was generated.
• Point getPoint() – Returns the x and y coordinates of mouse at which the event was
• generated.
• int getClickCount() – This method returns the number of mouse clicks for an event.
9. TextEvent :
The text event is generated when the user enters a character into a text field or a text
area. This event is identified by the following constant:
TEXT_VALUE_CHANGED
10. WindowEvent :
A window event is generated when a user performs any one of the window related
events which are identified by the following constants
Methods:
• Window getWindow() – Returns the reference of the window on which the event is
generated.
• Window getOppositeWindow() – Returns the reference to the previous window when
a focus event of activation event has occurred.
• int getOldState() – Returns an integer indicating the old state of the window.
• int getNewState() – Returns an integer indicating the new state of the window
1.ActionListener
This interface deals with the action events. Following is the event handling method
available in the ActionListener interface:
• void actionPerformed(ActionEvent ae)
2.AdjustmentListener
34 Unit 5 Notes – Java Programming
This interface deals with the adjustment event generated by the scroll bar. Following is
the event handling method available in the AdjustmentListener interface:
• void adjustmentValueChanged(AdjustmentEvent ae)
3.ComponentListener
This interface deals with the component events. Following are the event handling
methods available in the ComponentListener interface:
• void componentResized(ComponentEvent ce)
• void componentMoved(ComponentEvent ce)
• void componentShown(ComponentEvent ce)
• void componentHidden(ComponentEvent ce)
4.ContainerListener
This interface deals with the events that can be generated on containers. Following are the
event handling methods available in the ContainerListener interface:
• void componentAdded(ContainerEvent ce)
• void componentRemoved(ContainerEvent ce)
5.FocusListener
This interface deals with focus events that can be generated on different components or
containers. Following are the event handling methods available in the FocusListener
interface:
• void focusGained(FocusEvent fe)
• void focusLost(FocusEvent fe)
6.ItemListener
This interface deals with the item event. Following is the event handling method available
in the ItemListener interface:
• void itemStateChanged(ItemEvent ie)
7.KeyListener
This interface deals with the key events. Following are the event handling methods
available in the KeyListener interface:
• void keyPressed(KeyEvent ke)
• void keyReleased(KeyEvent ke)
• void keyTyped(KeyEvent ke)
8.MouseListener
This interface deals with five of the mouse events. Following are the event handling
methods available in the MouseListener interface:
• void mouseClicked(MouseEvent me)
• void mousePressed(MouseEvent me)
• void mouseReleased(MouseEvent me)
• void mouseEntered(MouseEvent me)
• void mouseExited(MouseEvent me)
35 Unit 5 Notes – Java Programming
9.MouseMotionListener
This interface deals with two of the mouse events. Following are the event handling
methods available in the MouseMotionListener interface:
• void mouseMoved(MouseEvent me)
• void mouseDragged(MouseEvent me)
10.MouseWheelListener
This interface deals with the mouse wheel event. Following is the event handling method
available in the MouseWheelListener interface:
• void mouseWheelMoved(MouseWheelEvent mwe)
11.TextListener
This interface deals with the text events. Following is the event handling method
available in the TextListener interface:
• void textValueChanged(TextEvent te)
12.WindowFocusListener
This interface deals with the window focus events. Following are the event handling
methods available in the WindowFocusListener interface:
• void windowGainedFocus(WindowEvent we)
• void windowLostFocus(WindowEvent we)
13.WindowListener
This interface deals with seven of the window events. Following are the event handling
methods available in the WindowListener interface:
• void windowActivated(WindowEvent we)
• void windowDeactivated(WindowEvent we)
• void windowIconified(WindowEvent we)
• void windowDeiconified(WindowEvent we)
• void windowOpened(WindowEvent we)
• void windowClosed(WindowEvent we)
• void windowClosing(WindowEvent we)
6. LAYOUT MANAGERS
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers. The
Layout manager is set by the following method.
Syntax:
void setLayout(LayoutManager layoutobj)
Each Layout manager keeps track of a list of components that are stored by their
name. The LayoutManager is notified each time you add a component to a container.
Types of Layout managers:
1) FlowLayout
2) BorderLayout
3) GridLayout
4) CardLayout
39 Unit 5 Notes – Java Programming
1) Flow Layout:
FlowLayout is the default layout manager. Components are laid out from the upper-left
corner, left to right and top to bottom. When no more components fits on a line, the next one
appears on the next line. A small space is left between each component.
Constructors of FlowLayout class:
a) FlowLayout()
- It creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
b) FlowLayout(int align)
- It creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
c) FlowLayout(int align, int hgap, int vgap)
- It creates a flow layout with the given alignment and the given horizontal
and vertical gap.
Flow Layout alignment:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
Example program:
public class flow extends Frame
{
public flow(String title )
{
super(title);
setLayout(new FlowLayout());
Button b1 = new Button(1);
Button b2 = new Button(2);
Button b3 = new Button(3);
Button b4 = new Button(4);
Button b5 = new Button(5);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
public static void main(String[] args)
{
flow f = new flow(“FlowLayout”);
f.setSize(300,300);
40 Unit 5 Notes – Java Programming
f.setVisible(true);
}
}
Output:
2) 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 frame or window.
Constructors of BorderLayout class:
a)BorderLayout()
- It creates a border layout but with no gaps between the components.
b)BorderLayout(int hgap, int vgap) - It creates a border layout with the given horizontal and
vertical gaps between the components.
BorderLayout alignment:
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout .EAST
BorderLayout .WEST
BorderLayout.CENTER
Example program:
public class BorderDemo extends Frame
{
public BorderDemo(String title)
{
super(title);
setLayout(new BorderLayout());
Button b1 = new Button("NORTH");
add(b1, BorderLayout.NORTH);
Button b2= new Button("CENTER");
add(b2, BorderLayout.CENTER);
Button b3= new Button("SOUTH");
add(b3, BorderLayout.SOUTH);
41 Unit 5 Notes – Java Programming
Button b4= new Button("EAST");
add(b4, BorderLayout.EAST);
Button b5= new Button("WEST");
add(b5, BorderLayout.WEST);
}
public static void main(String[] args)
{
BorderDemo b = new BorderDemo("Border Layout");
b.setSize(500,250);
b.setVisible(true);
}
}
Output:
3)GridLayout:
The GridLayout is used to arrange the components in a two-dimensional grid. When you
instantiate a GridLayout you can define the number of rows and columns. One component is
displayed in each rectangle.
Constructors of GridLayout class:
a)GridLayout()
- Creates a grid layout with one column per component in a row.
b)GridLayout(int rows, int columns)
- Creates a grid layout with the given rows and columns but no gaps between the
components.
c)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 program:
public class griddemo extends Frame
{
public griddemo(String title )
{
42 Unit 5 Notes – Java Programming
super(title);
setLayout(new GridLayout(3,3));
Button b1 = new Button(1);
Button b2 = new Button(2);
Button b3 = new Button(3);
Button b4 = new Button(4);
Button b5 = new Button(5);
Button b6 = new Button(6);
Button b7 = new Button(7);
Button b8 = new Button(8);
Button b9 = new Button(9);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
}
public static void main(String[] args)
{
griddemo g = new griddemo(“GridLayout”);
g.setSize(300,300);
g.setVisible(true);
}
}
Output:
4)Card Layout:
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
43 Unit 5 Notes – Java Programming
Constructors of CardLayout class:
a)CardLayout()
- Creates a card layout with zero horizontal and vertical gap.
b)CardLayout(int hgap, int vgap)
- Creates a card layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class:
public void next(Container parent): It is used to flip to the next card of the given container.
public void previous(Container parent): It is used to flip to the previous card of the given
container.
public void first(Container parent): It is used to flip to the first card of the given container.
public void last(Container parent): It is used to flip to the last card of the given container.
public void show(Container parent, String name): It is used to flip to the specified card with
the given name.
Example program:
public class carddemo extends Frame implements ActionListener
{
public carddemo(String title)
{
super(title);
setLayout(new CardLayout(20,20));
Button b1 = new Button("Apple ");
Button b2 = new Button ("Orange");
Button b3 = new Button("Banana");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener (this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
c.next(this);
}
}
public static void main(String args[])
{
carddemo c = new carddemo(“CardLayout”);
44 Unit 5 Notes – Java Programming
c.setSize(220,150);
c.setVisible(true);
}
Output:
7. MENUS
A menu bar displays a list of top-level menu choices. Each choice is associated with a
drop down menu. Each menu objects contains a list of MenuItem objects. Each MenuItem
object represents something that can be selected by the user.
• MenuBar: MenuBar holds the menus. MenuBar is added to frame with setMenuBar()
method.
• Menu: Menu holds the menu items. Menu is added to frame with add() method. A
sub-menu can be added to Menu.
• MenuItem: MenuItem displays the actual option user can select. Menu items are
added to menu with method addMenuItem().
• CheckboxMenuItem: It differs from MenuItem in that it appears along with a
checkbox. The selection can be done with checkbox selected.
Constructors in Menus:
1)Menu() - Constructs a new menu with an empty label.
2)Menu(String label) - Constructs a new menu with the specified label.
3)Menu(String label, boolean removable) - Constructs a new menu with the specified label,
indicating whether the menu can be float free.
Constructors in MenuItem:
1)MenuItem() - Constructs a new MenuItem with an empty label and no keyboard shortcut.
2)MenuItem(String label) - Constructs a new MenuItem with the specified label and no
keyboard shortcut.
3)MenuItem(String label, MenuShortcut s) - Create a menu item with an associated
keyboard shortcut.
45 Unit 5 Notes – Java Programming
Creation of menus involves many steps to be followed in an order. Following are the
steps.
1) Create menu bar
2) Add menu bar to the frame
3) Create menus
4) Add menus to menu bar
5) Create menu items
6) Add menu items to menus
Example program:
Public class menudemo extends Frame
{
menudemo()
{
Frame f= new Frame("Menu Example");
MenuBar mb=new MenuBar();
Menu m=new Menu("Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
m.add(i1);
m.add(i2);
m.add(i3);
mb.add(m);
f.setMenuBar(mb);
f.setSize(400,400);
f.setVisible(true);
}
}
public static void main(String args[])
{
new menudemo();
}
Output: