You are on page 1of 130

MODULE 3

B.Tech. CSE
Semester VI
Viswajyothi College of Engineering

1
I/O Basics

Streams
An abstraction that either produces or consumes
the information
Eg:- An input stream is an abstraction that can handle
different kinds of input : keyboard, disk file or network

Implemented in java.io.* package


Byte Stream and Character
Stream

Byte stream - for binary data


Character stream - for Unicode character data

Note: - Import java.io.* to use any of the stream


classes
4

Byte stream class

InputStream class and OutputStream Class


read() and write()

Both are abstract and overridden by sub classes


Character Stream class

Reader and Writer classes


read() and write()

Both are abstract and overridden by sub classes


Predefined Streams

All Java programs automatically import the java.lang


package.

System class defines three public static variables

System.in refers to standard input - InputStream

System.out refers to standard o/p


OutputStream
System.err refers to standard error
Reading Console Input
BufferedReader
BufferedReader(Reader inputReader) -
constructor
InputStreamReader(InputStream inputStream) -
constructor

BufferedReader br=new BufferedReader(new


InputStreamReader - converts bytes to System.in - console input
char InputStreamReader(System.in)) byte stream

Note: - br becomes a char based stream linked to


Reading Characters
read()
int read() throws IOException
It reads a char from input stream and returns an
integer value
Returns -1 at end of stream
read()
import java.io.*; Reads a char
class BRRead
{
public static void main(String args[]) throws
IOException
{
char c;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters. press q to quit");
do
{
c=(char) br.read();
System.out.println(c);
}while(c!='q');
}
readLine()
String readLine() throws IOException
import java.io.*; Reads a string
class console
{
public static void main(String args[]) throws IOException
{
String c;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Line of text. type stop to quit");
do
{
c=br.readLine();
System.out.println(c);
}while(!c.equals("stop"));
}
}
Writing Console output

print() or println() of PrintStream Class


System.out.write()
PrintWriter Class
PrintWriter(OutputStream outputstream, boolean
flushOnNewline)
java flushes the o/p stream every time a println is called
import java.io.*;
class console
{
public static void main(String args[]) throws
IOException
{
PrintWriter pw=new PrintWriter(System.out,true);
pw.println("This is a String");
int i=-1;
pw.println(i);
double d=4.5e-7;
pw.println(d);
Collections Framework

A standard which defines how a group of objects are


handled in your program.
Eg:- Linked List, Hash Table, Tree Set etc

In java.util
Collections Framework - Goals

1. High Performance
2. High Degree of inter operability among collections
3. Various algorithms to manipulate the collections
4. Extending/adapting collection had to be easy
5. Integration of standard arrays to collection
framework

Algorithms as static methods


An iterator interface allows to access elements in
the collection in a standard way
Several map interface and classes
interface interface
Collection Map

interface
interface interface interface
Set List Queue SortedMap

HashSet interface Vector ArrayList LinkedList TreeMap HashMap


SortedSet

Linked TreeSet
HashSet Implementations
Various Collection Interfaces
Collection
List
Set
SortedSet

Comparator
Iterator & ListIterator
RandomAccess
Collection
Foundation in which collection framework is built
Several Methods are declared

Several methods throw


UnsupportedOperationExcepti
on

21
List
Extends the collection
Stores a sequence of elements
Elements can be accessed/inserted by position
using a zero based index

Several methods throw


UnsupportedOperationExcepti
on

Set
Extends Collection
No additional methods

Set of elements without duplicate elements


SortedSet

Extends Set
Set in sorted way ie Ascending order

Several methods throw


NoSuchElementException

ClassCastException

NullPointerException
Collection Classes
Standard classes that implement the interfaces
The ArrayList Class
Extends AbstractList and Implements List
Supports dynamic array that can grow/shrink

ArrayList constructors
ArrayList()
ArrayList(Collection c)
ArrayList(int capacity)

Other methods:-
void ensureCapacity(int
cap)
import java.util.*;
class arraylistdemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
System.out.println("Initial Size of ArrayList is "+al.size());
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
System.out.println("After alteration the Size of ArrayList is
"+al.size());
System.out.println("The Contents are "+al);
al.remove("B");
al.remove(1);
System.out.println("After alteration the Size of ArrayList is
"+al.size());
System.out.println("The Contents are "+al);

}
}
Obtaining an array from ArrayList
import java.util.*;
class arraytoarraylist
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("The Contents are "+al);
Object temp[]=al.toArray();
int sum=0;
for(int i=0;i<temp.length;i++)
sum+=((Integer)temp[i]).intValue();
System.out.println(sum);
}
}
LinkedList Class
Extends AbstractSequentialList implements List
Constructors
LinkedList()
LinkedList(Collection c)
System.out.println("The Original List is
import java.util.*;
"+ l);
class ll
l.addFirst("A");
{
l.addLast("J");
public static void main(String
System.out.println("The New List is "+
args[])
l);
{
l.add(1, "A2");
LinkedList l=new
System.out.println("The New List is "+
LinkedList();
l);
l.add("B");
l.remove("A2");
l.add("C");
l.remove(2);
l.add("D");
System.out.println("The New List is "+
l.add("E");
l);
l.add("F");
l.removeFirst();
l.add("G");
l.removeLast();
l.add("H");
Object val=l.get(3);
l.add("I");
l.set(3, (String) val +" Changed");
System.out.println("The Final List is "+
l);
}
}
HashSet
Extends AbstractSet implements Set
Use Hash table for storage

Key Hash code

Hash code is used as the index at which data


associated with key is stored
Constructors
HashSet()
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillratio)
import java.util.*;
class hash
{
public static void main(String args[])
{
HashSet h=new HashSet();
h.add("B");
h.add("A");
h.add("D");
h.add("E");
h.add("C");
h.add("F");
System.out.println("The HashSet is "+ h);
}
}
LinkedHashSet
Extends HashSet
Maintains a linked list of the entries in the set
based on order of insertion

Output for previous program using LinkedHashSet


[B, A, D, E, C, F]
TreeSet Class
Implements Set that uses tree for storage
Elements are stored in ascending order

Constructors
TressSet()
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet s)
import java.util.*;
class tree
{
public static void main(String args[])
{
TreeSet t=new TreeSet();
t.add("B");
t.add("A");
t.add("D");
t.add("E");
t.add("C");
t.add("F");
System.out.println("The TreeSEt is "+ t);
}
}
Accessing a collection via
Iterator
Employ iterator/ListIterator interface to traverse the
list, remove or add elements

Iterator obtains or removes elements


ListIterator allows bidirectional traversal and
modification of elements
Methods in Iterator
Methods in ListIterator
To iterate

In all collections there is a iterator method

Steps:-
1. Obtain an iterator to the start of the collection by

calling the collections iterator()


2. Set up a loop that makes a call to hasNext()

which returns true or false


3. Traverse each element using next() function
import java.util.*;
class iteratordemo System.out.println("\nModified List is ");
{ itr=al.iterator();
public static void main(String args[]) while(itr.hasNext())
{ {
ArrayList al=new ArrayList(); Object element=itr.next();
al.add("A"); System.out.print(element +" ");
al.add("B"); }
al.add("C");
al.add("D"); System.out.println("\nPrinting in reverse ord
while(ltr.hasPrevious())
al.add("E");
System.out.println("The Original List is {
"); Object element=ltr.previous();
System.out.print(element +" ");
Iterator itr=al.iterator(); }
while(itr.hasNext())
{ }
Object element=itr.next();
System.out.print(element +" "); }
}

ListIterator ltr=al.listIterator();
while(ltr.hasNext())
{
Object element=ltr.next();
ltr.set(element+"+");
Storing userclassdefined
address
classes in
collections
import java.util.*;
{
public static void main(String args[])
class mailing {
{ LinkedList l=new LinkedList();
String name; l.add(new mailing("J.W West","11 Oack Ave","Urbana,
String street; "Georgia ,"678934"));
String city; l.add(new mailing("Ralph Baker","1421 Maple Lane",
String state; "Mahomet","Washington","672213"));
String zip; l.add(new mailing("Tom Carlton","867 Elm Street",
mailing(String n, String s, "Champaign","IL","687543"));
String c, String st, String z)
{ Iterator itr=l.iterator();
name=n; while(itr.hasNext())
street=s; {
city=c; Object element=itr.next();
state=st; System.out.print(element +"\n");
zip=z; }
} }
public String toString() }
{
return name + "\n"
+street+"\n"+city+"\n"+state+"\n"+zip+"
\n\n";
}
Maps
An object which stores association with keys and
values
Keys and values are objects
Keys must be unique, values can be duplicated
Map Interfaces

1. Map
2. SortedMap
3. Map.Entry
Map Interface
Given a key and value you can store the value in Map
object
After the value is stored,you can retrieve it using the
key

get(Object)
put(Object k ,Object v)

entrySet() returns Set that contains entries in the

map May raise


KeySet() - returns Set NoSuchElementException
that contains keys in the map
ClassCastException
Note: - Methods in page 463 NullPointerException
UnSupportedOperationExce
SortedMap Interface
Extends Map
Entries are maintained in ascending key order

May raise
NoSuchElementExceptio
ClassCastException
Note: - Methods in page 465 NullPointerException
Map.Entry interface
To work with map entry
Pls recall:-
entrySet() returns Set,each of these entries is a

Map.entry object

Note: - Methods in page 466


Map Classes
AbstractMap
HashMap
TreeMap
WeakHashMap
LinkedListMap
IdentityHashMap
HashMap
Uses hash table to implement HashMap

HashMap()
HashMap(Map m)
HashMap(int cap)
HashMap(int cap, float fillratio)
import java.util.*;
class hashmap
{
public static void main(String args[])
{
HashMap hm=new HashMap();
hm.put("A",new Double(1000));
hm.put("B",new Double(2000));
hm.put("C",new Double(3000));
hm.put("D",new Double(4000));
hm.put("E",new Double(5000));

Set s=hm.entrySet();
Iterator i=s.iterator();
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next();
System.out.print(me.getKey()+ ":");
System.out.println(me.getValue());
}
}
}
TreeMap
Implements Map
Storing key/value pair in sorted order

TreeMap()
TreeMap(Comparator c)
TreeMap(Map m)
TreeMap(SortedMap sm)
import java.util.*;
class treemap
{
public static void main(String args[])
{
TreeMap tm=new TreeMap();
tm.put("A",new Double(1000));
tm.put("B",new Double(2000));
tm.put("C",new Double(3000));
tm.put("D",new Double(4000));
tm.put("E",new Double(5000));
Set s=tm.entrySet();
Iterator i=s.iterator();
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next();
System.out.print(me.getKey()+ ":");
System.out.println(me.getValue());
}
}
}
LinkedHashMap
Extends HashMap
Maintains a linkedlist of entries in the map in the
order in which they are entered

LinkedHashMap()
LinkedHashMap(Map m)
LinkedHashMap(int cap)
LinkedHashMap(int cap, float fillratio)
LinkedHashMap(int cap, float fillratio, boolean
order)
Comparator
To sort elements in collection and maps
Eg:- TreeSet and TreeMap

Specify a Comparator object when creating a set


or map

int compare(Object obj1, Object obj2)


0 (obj1 = obj2)
+ve (obj1 > obj2)
-ve (obj1 < obj2)
boolean equals(Object obj)
import java.util.*; class CompDemo
class MyComp implements Comparator {
{ public static void main(String args[])
public int compare(Object a, Object {
b)
{ TreeSet ts = new TreeSet(new MyComp
String aStr, bStr; ts.add("C");
aStr = (String) a; ts.add("A");
bStr = (String) b; ts.add("B");
// reverse the comparison ts.add("E");
return bStr.compareTo(aStr); ts.add("F");
} ts.add("D");
// no need to override equals
} Iterator i = ts.iterator();

while(i.hasNext())
{
Object element = i.next();
System.out.print(element + " ");
}
System.out.println();
}
}
OUTPUT :- Tree is now stored in reverse
order:
The Collection Algorithms
Predefined algorithms that can be used with
collections and maps
Defined as static methods in Collections class
Continuation at page 478 & 479
import java.util.*; System.out.println();
class algorithm Collections.shuffle(ll);
{ itr=ll.iterator();
public static void main(String args[])
while(itr.hasNext())
{ {
LinkedList ll=new LinkedList(); Object element=itr.next();
ll.add(new Integer(10)); System.out.print(element +" ");
ll.add(new Integer(6)); }
ll.add(new Integer(-1)); System.out.println();
ll.add(new Integer(2));
System.out.println("Minimum="+Collections.min(l
ll.add(new Integer(39));
ll.add(new Integer(-100));
System.out.println("Minimum="+Collections.max(
}
}
Comparator r=Collections.reverseOrder();
Collections.sort(ll,r);
Iterator itr=ll.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element +" ");
}
Arrays class
Applet
Small applications accessed over the internet
server, transported over the internet,
automatically installed and executed by the client

Limited access to the resources of the client


platform
import java.awt.*;
import java.applet.*;
/*
<applet code=simpleapp.class width=200
height=60>
</applet>
*/

public class simpleapp extends Applet


{
public void paint(Graphics g)
{
g.drawString("Hello S6 CS A", 20,20);
}
} ways to run an applet
Two
1.Appletviewer Save file as simpleapp.java
2.Web browser Compile javac simpleapp.java
Execute appletviewer simpleapp.
Abstract Window
import java.awt.*; Toolkit, for GUI
import java.applet.*; applet , for Applet class
/*
<applet code=simpleapp.class width=200
height=60> Source code is
</applet> documented
with prototype of HTML
*/ statements
Always (public and
public class simpleapp extends Appletextends Applet)
{ Called to redraw applet
Over ridden method[class App
public void paint(Graphics g)
{
g.drawString("Hello S6 CS A", 20,20);
}
}
Note: -
No main()
Graphics defines the graphics context
Applet Architecture
Applet is a window based event driven program
Resembles a set of interrupt service routines

applet waits until an event occurs


AWT will notify about the event

handled by the event handler in applet

return control to AWT

User initiates interaction with applet


no prompting like console
users interact with applet as he/she wants it

events are generated and handled


Applet Skelton
Applet programs overrides
init(), start(), stop() and destroy() of Applet class
and paint() by AWT

When an applet is called AWT calls the methods in this


order
init()
start()
paint()
When an applet is terminated these methods are called
stop()
destroy()
import java.awt.*;
import java.applet.*;
/*
<applet code=skeleton.class width=200 height=60>
</applet>
*/
public class skeleton extends Applet
{
public void init()
{
// Initialization
}
public void start()
{
// Start or resume execution
}
public void stop()
{
//Suspends execution
}
public void destroy()
{
//shutdown activities
}
public void paint(Graphics g)
{
//redraw applet
}
}
init()
first method to be called
initialization of variables
called only once
start()
called after init()
called each time when applet has started
ie when a browser is closed and opened
paint()
When redrawn
Graphics context graphical environment
stop()
when browser is closed or leaves to another page
suspends the applet thread
destroy()
When the applet is completely removed from the memory
Applet Display Methods
drawString(String msg,int x,int y)
void setBackground(Color newcolor)
void setForeground(Color newcolor)
Color getBackground()
Color getForeground()
showStatus(text message

Eg: - Color.black
import java.awt.*;
import java.applet.*;
/* Passing Parameters to
<applet code=parameter applet
public class parameter extends Applet
width=300 height=80> {
<param name=fontName String fontname;
value=TimesnewRoman> int size;
<param name=fontSize value=14> float leading;
<param name=leading value=2> boolean active;
<param name=accountEnabled value=true>
</applet> public void start()
{
*/ String param;
fontname=getParameter("fontName");
size=Integer.parseInt(getParameter("fontSize"));
leading=Float.valueOf(getParameter("leading"))
.floatValue();
active=Boolean.valueOf(getParameter("account"
.booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font Name :"+fontname,0,10)
g.drawString("Font Size :"+size,0,30);
g.drawString("Leading :"+leading,0,60);
g.drawString("Account Active:"+active,0,90);

}
}
Events

Applets are event driven program


java.awt.event package

An event is an object that describes a state change in a source


Generated as a consequence of a person interacting with the
elements in a GUI

Eg:-
Pressing a button
Enter a character using keyboard
Mouse clicks
Delegation event model

Source generates an event and sends it to one or more


listeners
Once received the listener processes the event and then
returns
Event Source
Object that generates an event
Due to change in internal state of the object
Source must register listeners

public void addTypeListener(TypeListener el)


Type is the name of the event

el is the reference to the listener

Eg:- addKeyListener(), addMouseMotionListener()

public void removeTypeListener(TypeListener el)


Event Listener

The object that is notified when an event occurs

Listeners must be
1. Registered with the source

2. Implement methods to receive and process the

event

Eg: - MouseMotionListener interface


Event Classes

EventObject is the super class of all events in java


AWTEvent is the super class of all events in AWT

EventObject Methods:-
Object getSource()

toString()
Action Event Class
Generated when a button is pressed,a list item is double clicked
or a menu item is selected

Defines 4 integers which defines modifiers which is passed along


with the event ALT_MASK,CTRL_MASK,META_MASK,SHIFT_MASK

ActionEvent(Object src,int type,String cmd)


ActionEvent(Object src,int type,String cmd,int modifier)
ActionEvent(Object src,int type, String cmd,long when, int
modifier)

String getActionCommand() For example, button press returns


command name equal to label of the button
AdjustmentEvent Class
Generated by scrollbar
Define the following integer constants

getAdjustable() returns object


getAdjustmentType() returns constant
getValue() retuns amount of adjustment
The ComponentEvent
class
Generated when size, position or visibility of a component is changed

ComponentEvent is the superclass either directly or indirectly of


ContainerEvent,FocusEvent, KeyEvent, MouseEvent, and
WindowEvent.
Component getComponent( )
ContainerEvent Class

Generated when a component is added/removed from a


container

COMPONENT_ADDED, COMPONENT_REMOVED

ContainerEvent(Component src, int type, Component comp)

Container getContainer( )
Component getChild( )
FocusEvent class

When a component gains or looses input focus

FOCUS_GAINED, FOCUS_LOST

FocusEvent(Component src,int type)


FocusEvent(Component src,int type,boolean tempflag)
FocusEvent(Component src,int type, boolean tempflag Componen
other)

Component getOppositeComponent( )
boolean isTemporary( )
InputEvent class
Sub classes are KeyEvent and MouseEvent

InputEvent defines several integer constants


that represent any modifiers, such as the control
key being pressed, that might be associated with
the event.
KeyEvent Class
When keyboard input occurs

KEY_PRESSED, KEY_RELEASED, KEY_TYPED

KeyEvent(Component src, int type, long when,int modifier, int


code)
KeyEvent(Component src, int type, long when,int modifier, int
code,char ch)

char getKeyChar( )
int getKeyCode( )
MouseEvent Class

MouseEvent(Component src, int type, long when, int modifier,int x, int y,int clicks,
boolean triggerspopup)

getX()
geyY()
The MouseWheelEvent Class
WHEEL_BLOCK_SCROLL, WHEEL_UNIT_SCROLL
MouseWheelEvent(Component src, int type, long
when, int modifier,int x, int y,int clicks, boolean
triggerspopup,int scrollhow,int amount,int count)

int getWheelRotation( )
int getScrollType( )
int getScrollAmount( )
ItemEvent Class

When a check box or a list item is clicked or when a


checkable menu item is selected or deselected
DESELECTED, SELECTED

ItemEvent(ItemSelecteable src, int type,Objcet entry,int


state)

Object getItem( )
ItemSelectable getItemSelectable( )
int getStateChange( )
Text Event Class
When char are entered in the text fields
TEXT_VALUE_CHANGED
TextEvent(Object src,int type)
WindowEvent class

Window getWindow( )
EventListener Interfaces
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code= AnAppletWithButtons width=200 height=60>
</applet>
*/
public class AnAppletWithButtons extends Applet implements ActionListener
{
Button button1, button2;
public void init()
{
button1 = new Button("Button 1");
add(button1);
button1.addActionListener(this);

button2 = new Button("Button 2");


add(button2);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button1)
System.out.println("Button 1 was pressed");
else
System.out.println("Button 2 was pressed");
}
}
import java.awt.*; public void mouseExited(MouseEvent me)
import java.awt.event.*; {
import java.applet.*; mousex=0;
/* mousey=10;
<applet code= mouseevent width=200 height=60> msg="Mouse Exited";
</applet> repaint();
*/ }
public class mouseevent extends Applet implements
public void mousePressed(MouseEvent me)
MouseListener, MouseMotionListener {
{ mousex=me.getX();
String msg=""; mousey=me.getY();
int mousex=0,mousey=0; msg="Mouse Button Presses";
public void init() repaint();
{ }
addMouseListener(this); public void mouseReleased(MouseEvent me)
addMouseMotionListener(this); {
} mousex=me.getX();
public void mouseClicked(MouseEvent me) mousey=me.getY();
{ msg="Mouse Button Released";
mousex=0; repaint();
mousey=10; }
msg="Mouse Clicked"; public void mouseDragged(MouseEvent me)
repaint(); {
} mousex=me.getX();
public void mouseEntered(MouseEvent me) mousey=me.getY();
{ msg="*";
mousex=0; showStatus("Dragging Mouse at " + mousex+
mousey=10; ","+mousey);
msg="Mouse Entered"; repaint();
repaint(); }
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving Mouse at " + me.getX()+
","+me.getY());

public void paint(Graphics g)


{
g.drawString(msg,mousex,mousey);
}

}
import java.awt.*;
import java.awt.event.*;
import java.applet.*; Handling Keyboard Events
/*
<applet code= keyboardevent width=200 height=60>
</applet>
*/
public class keyboardevent extends Applet implements KeyListener
{ public void keyPressed(KeyEvent ke)
String msg=""; {
int x=10,y=20; showStatus("Key Down");
}
public void init()
{ public void keyReleased(KeyEvent ke)
addKeyListener(this); {
requestFocus(); showStatus("Key Up");
} }

public void keyTyped(KeyEvent ke)


{
msg+=ke.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,x,y);
}
95

AWT
The AWT contains numerous classes and methods
that allow you to create and manage windows

AWT Classes - pg 688, Table 21-1


.

All elements that comprise a GUI are derived from the abstract class
Component.
A container is a component that can accommodate other components
Container provides the overloaded method add () to include
components in the container
AWT Controls

Labels
Push Button
Check Box
Choice List
Lists
Scroll Bars
Text Editing
To add and remove

Methods defined in Container

Component add(Component obj)


void remove(Component obj)
void removeall()
Labels
It contains a string, which it displays

Label()
Label(String str)
Label(String str, int how)
how- Label.LEFT, .RIGHT,.CENTER

void setAligment(int how)


int getAlignment()

String getText()
void setText(String str)
import java.awt.*;
import java.applet.*;
/*
<applet code= label width=200 height=60>
</applet>
*/

public class label extends Applet


{
public void init()
{
Label one=new Label("One");
Label two=new Label("Two");
Label three=new Label("Three");
add(one);
add(two);
add(three);
}
Button

Contains a label and generates an event when


presses

Button()
Button(String str)

After creation
void setLabel(String str)
String getLabel()
import java.awt.*;
import java.awt.event.*; public void actionPerformed(ActionEven
import java.applet.*; {
/* String str=ae.getActionCommand();
<applet code= button width=200 if(str.equals("Yes"))
height=60> yes.setLabel("Yes Clicked");
</applet> else if(str.equals("No"))
*/ no.setLabel("No Clicked");
public class button extends Applet else
implements ActionListener maybe.setLabel("Maybe Clicked");
{ repaint();
Button yes,no,maybe; }
}
public void init()
{
yes=new Button("Yes");
no=new Button("No");
maybe=new Button("Maybe");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
CheckBox
Contains a label and used to turn an option on or off. It
consists of a small box with a check mark or not.

Checkbox()
Checkbox(String str)
Checkbox(String str, Boolean on)
Checkbox(String str, Boolean on, CheckboxGroup cbgroup)
Checkbox(String str, CheckboxGroup cbgroup, Boolean on)

boolean getState()
void setState(boolean on)
String getLabel()
void setLabel(String str)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= checkbox width=200 height=60>
</applet>
*/

public class checkbox extends Applet implements public void itemStateChanged(ItemEve


ItemListener {
{ repaint();
String msg=""; }
Checkbox win98,win2000,winxp,win7; public void paint(Graphics g)
public void init() {
{ msg="Current Status";
win98=new Checkbox("Windows 98",null,false); g.drawString(msg,6,80);
win2000=new Checkbox("Windows 2000",null,false); msg="Windows 98:"+ win98.getState
winxp=new Checkbox("Windows XP",null,false); g.drawString(msg,6,100);
win7=new Checkbox("Windows 7",null,false); msg="Windows 2000:"+
add(win98); win2000.getState();
add(win2000); g.drawString(msg,6,120);
add(winxp); msg="Windows XP:"+ winxp.getState
add(win7); g.drawString(msg,6,140);
win98.addItemListener(this); msg="Windows 7:"+ win7.getState();
win2000.addItemListener(this); g.drawString(msg,6,160);
winxp.addItemListener(this);
win7.addItemListener(this);
} }
10
5
CheckBoxGroup
Set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These
check boxes are often called radio buttons

Eg:- Checkbox getSelectedCheckbox( )


void
Checkbox Win98, winNT, setSelectedCheckbox(Checkbox
solaris, mac;
CheckboxGroup cbg; which)
public void init()
{
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("MacOS", cbg, false);
}
Choice Controls

Creates a popup menu where user chooses

Choice()

void add(String str); - To add menu items


String getItem(int index)
String getSelectedItem()
int getSelectedIndex()
int getItemCount()
void select(int index)
void select(String name)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= choice width=200 height=60>
</applet>
*/
public class choice extends Applet implements ItemListener
{
String msg="";
Choice os,browser; public void itemStateChanged(ItemEvent ie)
public void init() {
{ repaint();
os=new Choice(); }
browser=new Choice(); public void paint(Graphics g)
os.add("Windows 98"); {
os.add("Windows 2000"); msg="Current OS: "+os.getSelectedItem();
os.add("Windows xp"); g.drawString(msg,6,120);
os.add("Windows 7"); msg="Browser: "+
browser.add("InternetExplorer"); browser.getSelectedItem();
browser.add("Mozilla Firefox"); g.drawString(msg,6,140);
browser.add("Google Chrome"); }
browser.add("Netscape"); }
add(os);
add(browser);
os.select("Windows 7");
browser.select(2);
os.addItemListener(this);
browser.addItemListener(this);
}
List
Multiple choice, scrolling selection list

List()
List(int numrows)
List(int numrows, boolean multipleselect)

To add
void add(String name) // add to end of the list
void add(String name,int index) // to index
String getSelectedItem()
int getSelectedIndex()
String [] getSelectedItems()
int[] getSelectedIndexes()
int getItemCount()
void select(int index)
import java.awt.*; public void itemStateChanged(ItemEvent ie)
import java.awt.event.*; {
import java.applet.*; repaint();
/* }
<applet code= list width=200 height=60>
</applet> public void paint(Graphics g)
*/ {
public class list extends Applet implements int idx[];
ItemListener idx=digit.getSelectedIndexes();
{ msg="Current Values: ";
String msg=""; for(int i=0;i<idx.length;i++)
List digit,words; msg+=digit.getItem(idx[i])+" ";
public void init() g.drawString(msg,6,120);
{ msg="words: "+ words.getSelectedItem();
digit=new List(4,true); g.drawString(msg,6,140);
words=new List(4,false); }
digit.add("1"); }
digit.add("2");
digit.add("3");
digit.add("4");
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");

add(digit);
add(words);
digit.select(3);
words.select(3);

digit.addItemListener(this);
words.addItemListener(this);
Scroll Bars
Scroll bars are used to select continuous values between a
specified minimum and maximum. Scroll bars may be
oriented horizontally or vertically

Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialvalue, int thumbSize, int min, int max)
Scrollbar.VERTICAL
Scrollbar.HORIZONTAL
void setValues(int initialValue, int thumbSize, int min, int max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
TextField
Single line text entry
Textfield()
Textfield(int numchars)
Textfield(String str)
Textfield(String str,int numchars)

String getText()
void setText(String str)
String getSelectedText()
void select(int startindex,int endindex)
boolean isEditable()
void setEditable(boolean canedit)
void setEchoChar(char ch)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= list width=200 height=60>
</applet>
*/
public class text extends Applet implements ActionListener
{
TextField name,password; public void actionPerformed(ActionEvent ae)
Label n,p; {
public void init() repaint();
{ }
name=new TextField(12); public void paint(Graphics g)
password=new TextField(8); {
password.setEchoChar('*'); g.drawString("Name:"+name.getText(),6,60);
n=new Label("Name",Label.RIGHT); g.drawString("Selected Text in Name:
p=new Label("Password",Label.RIGHT); +name.getSelectedText(),6,80
add(n); g.drawString(Password:"+password.getText(),6
add(name); }
add(p);
add(password); }
name.addActionListener(this);
password.addActionListener(this);

}
TextArea

Multi line text editor

TextArea()
TextArea(int numLines,int numchars)
TextArea(String str)
TextArea(String str, int numLines,int numchars)
TextArea(String str, int numLines,int numchars,int
sbars)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= textarea width=200 height=60>
</applet>
*/
public class textarea extends Applet
{

public void init()


{
String st="We aim to provide you with the worlds strongest security and privacy
tools\n."+
" Security and privacy matter to us, we know how important they are to you and we work
hard \n"+
" to get them right. Our Good to Know site helps you and your family stay safe online.\n"+
" Visit to learn more and understand how Google helps protect you, your computer and
the\n"+
" Internet from cybercrime.";
TextArea text=new TextArea(st);
add(text);
}
}
Layout manager
All components are positioned by the default layout man
Arranges the controls within a window using some algor
Each container has a layout manager

setLayout(LayoutManager layoutObj)
If no call to setLayout default layout manager is used
FlowLayout

Default layout manger


Components are laid out from upper left corner, Left to
right and Top to bottom

FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int ver)
how takes values FlowLayout.LEFT,.CENTER,.RIGHT
Space b/w components in horz and ver
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));

.
}
Border Layout

Has four , narrow fixed-width components at the edges


and one large area in the center
The four sides are referred as north, south, east and west
Middle area is called as the center

BorderLayout()
BorderLayout(int horz,int vert)

add(Component obj, Object region)


region takes values
BorderLayout.CENTER,.EAST,SOUTH,NORTH,WEST
import java.awt.*;
import java.util.*;
import java.applet.*;
/*
<applet code= borderlayout width=200 height=60>
</applet>
*/

public class borderlayout extends Applet


{
public void init()
{
setLayout(new BorderLayout());
add(new Button("TOP"),BorderLayout.NORTH);
add(new Label("This is the
footer"),BorderLayout.SOUTH);
add(new Button("RIGHT"),BorderLayout.EAST);
add(new Button("LEFT"),BorderLayout.WEST);
String
msg="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAA";
add(new TextArea(msg),BorderLayout.CENTER);
}
GridLayout

Lay components in 2d grid

GridLayout()
GridLayout(int rows,int cols)
GridLayout(int rows,int cols,int horz,int vert)
import java.awt.*;
import java.applet.*;
/*
<applet code= gridlayout width=200
height=60>
</applet>
*/
public class gridlayout extends Applet
{
public void init()
{
int k=1;
setLayout(new GridLayout(4,4));
for(int i=1;i<16;i++)
{
add(new Button(""+k));
k++;
CardLayout

Can hold other layouts


Cards form the deck

PANEL
Class

CardLayout();
CardLayout(int horz,int vert)

void add(Component panelobj, Object name)


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= cardlayout width=200 height=60>
</applet>
*/
public class cardlayout extends Applet implements
ActionListener,MouseListener
{
Checkbox win98,win2000,redhat,ubuntu; Panel win=new Panel();
Panel os; Panel lin=new Panel();
CardLayout card; win.add(win98);
Button windows,linux; win.add(win2000);
PANELS lin.add(redhat);
public void init() lin.add(ubuntu);
{
windows=new Button("Windows"); os.add(win,"Windows");
linux=new Button("Linux"); os.add(lin,"Linux");
add(windows); add(os);
add(linux); Card panels
card=new CardLayout();
added to windows.addActionListener(this);
linux.addActionListener(this);
os=new Panel(); Panel addMouseListener(this);
os.setLayout(card); }
win98=new Checkbox("Windows 98",null,false);
win2000=new Checkbox("Windows 2000",null,false);
redhat=new Checkbox("RedHat",null,false);
public void mousePressed(MouseEvent me)
{
card.next(os);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{

}
public void mouseExited(MouseEvent me)
{

}
public void mouseReleased(MouseEvent me)
{
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==windows)
{
card.show(os,"Windows"); // Shows card name passed as
argument
}
else
card.show(os,"Linux");
}
MenuBar
Menu
MenuItem
import java.awt.*; public class menu extends Applet
import java.applet.*; {
import java.awt.event.*; Frame f;
/* public void init()
<applet code= menu width=200 height=60> {
</applet> f=new menuframe("My Menu");
*/ setSize(new Dimension(500,500)); // For Applet
class menuframe extends Frame f.setSize(500,500); // For Frame
{ f.setVisible(true);
}
menuframe(String title) public void start()
{ {
super(title); // Title for Frame f.setVisible(true);
MenuBar mbar=new MenuBar(); }
setMenuBar(mbar); public void stop()
{
Menu file=new Menu("File"); f.setVisible(false);
MenuItem item1,item2,item3; }
file.add(item1=new MenuItem("New")); }
file.add(item2=new MenuItem("Open"));
file.add(item3=new MenuItem("Exit"));
mbar.add(file);

Menu edit=new Menu("Edit");


MenuItem item4,item5,item6;
edit.add(item4=new MenuItem("Cut"));
edit.add(item5=new MenuItem("Copy"));
edit.add(item6=new MenuItem("Paste"));
mbar.add(edit);
}
}
Note: - Pg 693: - Fram
12
7
Swings
Swing is a set of classes that provides more
powerful and flexible components than are
possible with the AWT.

Lightweight Components - They are written


entirely in Java and, therefore, are platform-
independent.
JApplet
JApplet class, which extends Applet.
Applets that use Swing must be subclasses of
JApplet.

When adding a component to an instance of


JApplet, do not invoke the add( ) method of the
applet.
Instead, call add( ) for the content pane of the
Japplet object.
Container getContentPane( )
The add( ) method of Container can be used to
add a component to a content pane.
void add(component)
Contentpane Layer used to hold obje
JButton
JButton allows an icon, a string, or both to be
associated with the push button.

JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends Japplet implements ActionListener
{
JTextField jtf;
public void init()
{ ImageIcon italy = new ImageIcon("italy.gif"
Container contentPane = getContentPane();
jb = new JButton(italy);
contentPane.setLayout(new FlowLayout());
jb.setActionCommand("Italy");
ImageIcon france = new ImageIcon("france.gif"); jb.addActionListener(this);
JButton jb = new JButton(france); contentPane.add(jb);
jb.setActionCommand("France");
jb.addActionListener(this);
ImageIcon japan = new ImageIcon("japan.g
contentPane.add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(japan);
jb = new JButton(germany); jb.setActionCommand("Japan");
jb.setActionCommand("Germany"); jb.addActionListener(this);
jb.addActionListener(this); contentPane.add(jb);
contentPane.add(jb);

jtf = new JTextField(15);


contentPane.add(jtf);
}

public void actionPerformed(ActionEvent a


{
jtf.setText(ae.getActionCommand());
}

You might also like