Java 3rd Module (4)
Java 3rd Module (4)
AWT represents a class library to develop applications using GUI. The [Link]
package consists of classes and interfaces to develop GUIs.
Panel: Panel class is a subclass of Container and is a super class of Applet. When screen output
is redirected to an applet, it is drawn on the surface of the Panel object. In, essence panel is a
window that does not contain a title bar, menu bar or border.
Window: A window represents a rectangular area on the screen without any borders or title
bar. The Window class create a top-level window.
Frame: It is a subclass of Window and it has title bar, menu bar, border and resizing windows.
The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. Its concept is quite simple: a source generates an event and sends it
to one or more listeners.
In this scheme, the listener simply waits until it receives an event. Once an event is received,
the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that
generates those events.
A user interface element is able to ―delegate‖ the processing of an event to a separate
piece of code. In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only to
listeners that want to receive them.
Events: An event is an object that describes a state change in a source. It can be generated as
a consequence of a person interacting with the elements in a GUI. Some of the activities
that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.
Event Sources: A source is an object that generates an event. Generally sources are
components. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has its own registration method.
Here is the general form:
public void addTypeListener (TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ).
A source must also provide a method that allows a listener to unregister an
interest in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )
Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
[Link] package.
Sources of Events:
The [Link] package provides many event classes and Listener interfaces for
event handling. At the root of the Java event class hierarchy is EventObject, which is in
[Link]. It is the super class for all events. It‘s one constructor is shown here:
EventObject(Object src) - Here, src is the object that generates this event.
Method Description
public void add(Component c) inserts a component.
sets the size (width and height) of the
public void setSize(int width,int height)
component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
changes the visibility of the component, by
public void setVisible(boolean status)
default false.
The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or
a menu item is selected.
The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK (Ex.
Escape), and SHIFT_MASK.
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( ) -Returns the command string associated
with this action
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
The getComponent( ) method returns the component that generated the event. It is
shown here:
Component getComponent( )
The ContainerEvent Class:
A ContainerEvent is generated when a component is added to or removed from a
container. There are two types of container events. The ContainerEvent class defines
constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.
However, because of possible conflicts between the modifiers used by keyboard events and
mouse events, and other issues, the following extended modifier values were added:
META_DOWN_MASK SHIFT_DOWN_MASK
Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their forms
are shown here:
int getX( )
int getY( )
An event listener registers with an event source to receive notifications about the events
of a particular type. Various event listener interfaces defined in the [Link] package
are given below:
Interface Description
Defines the actionPerformed() method to receive and process
ActionListener action events.
void actionPerformed(ActionEvent ae)
Defines five methods to receive mouse events, such as when a
mouse is clicked, pressed, released, enters, or exits a component
void mouseClicked(MouseEvent me)
MouseListener void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Defines two methods to receive events, such as when a mouse is
dragged or moved.
MouseMotionListener
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Defines the adjustmentValueChanged() method to receive and
AdjustmentListner process the adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
Defines the textValueChanged() method to receive and process an
TextListener event when the text value changes.
void textValueChanged(TextEvent te)
Defines seven window methods to receive events.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
WindowListener
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Defines the itemStateChanged() method when an item has been
ItemListener
void itemStateChanged(ItemEvent ie)
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or
WindowFocusListener loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
This interface defines four methods that are invoked when a
component is resized, moved, shown, or hidden. Their general
forms are shown here:
ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
This interface contains two methods. When a component is added
to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( )
ContainerListener is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
This interface defines two methods. When a component obtains
keyboard focus, focusGained( ) is invoked. When a component
loses keyboard focus, focusLost( ) is called. Their general forms
FocusListener
are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
This interface defines three methods.
void keyPressed(KeyEvent ke)
KeyListener
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
Registration Methods:
For registering the component with the Listener, many classes provide the registration
methods. For example:
Button
o public void addActionListener(ActionListener a){}
MenuItem
o public void addActionListener(ActionListener a){}
TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
TextArea
o public void addTextListener(TextListener a){}
Checkbox
o public void addItemListener(ItemListener a){}
Choice
o public void addItemListener(ItemListener a){}
List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Mouse
o public void addMouseListener(MouseListener a){}
Handling Mouse Events Example Program:
}
public void mouseClicked(MouseEvent me)
{
msg="mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{ msg="mouse entered";repaint();
}
public void mouseExited(MouseEvent me){
msg="mouse exited";repaint();
}
public void mousePressed(MouseEvent me){
msg="mouse pressed";repaint();
}
public void mouseReleased(MouseEvent me){
msg="mouse released";repaint();
}
public void paint(Graphics g)
{
[Link](msg,200,200);
}
}
class MouseEventsExample
{
public static void main(String arg[])
{
MouseDemo d=new MouseDemo();
[Link](400,400);
[Link](true);
[Link]("Mouse Events Demo Program");
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
10
Output:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements KeyListener
{
String keystate="Hello GFG";
String msg="";
MyFrame()
{
addKeyListener(this);
addWindowListener(new MyWindow() );
}
public void keyPressed(KeyEvent ke)
{
keystate="Key Pressed";
msg+=[Link]( [Link]());
repaint();
}
public void keyTyped(KeyEvent ke)
{
keystate="Key Typed"; repaint();
msg=msg+[Link]();
}
public void keyReleased(KeyEvent ke)
{
keystate="Key Released"; repaint();
}
public void paint(Graphics g)
{
[Link](keystate,100,50);
[Link](msg,100,100);
}
11
}
class KeyEventsExample
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link]("Key Events Example");
[Link](500,300);
[Link](true);
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Adapter Classes:
Java provides a special feature, called an adapter class, that can simplify the creation
of event handlers in certain situations. An adapter class provides an empty implementation of
all methods in an event listener interface. Adapter classes are useful when you want to receive
and process only some of the events that are handled by a particular event listener interface.
For example,
MouseListener MouseAdapter
void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }
void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }
void mouseExited(MouseEvent me) void mouseExited(MouseEvent me) { }
void mousePressed(MouseEvent me) void mousePressed(MouseEvent me) { }
void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }
Example Program
import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;
13
WindowEx1(){
addWindowListener(new WA());
}
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
class WindowAdapterEx
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
}
}
Inner Classes:
Inner class is a class defined within another class, or even within an expression.
Example:
import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WA());
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
}
class WindowAdapterInner
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
14
}
}
Example:
import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
class WindowAdapterAnonymous
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
}
}
Control Fundamentals:
The AWT supports the following types of controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text Editing
These controls are subclasses of Component
Adding and Removing Controls: To include a control in a window, you must add it to the
window. To do this, you must first create an instance of the desired control and then add it to
a window by calling add(), which is defined by Container.
The General form is:
15
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to compObj is
returned.
Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove( ). This method is also defined by Container. Here is
one of its forms:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll( ).
The HeadlessException:
Most of the AWT controls have constructors that can throw a HeadlessException when
an attempt is made to instantiate a GUI component in a non-interactive environment (such as
one in which no display, mouse, or keyboard is present).
Labels:
A label is an object of type Label, and it contains a string, which it displays. Labels are
passive controls that do not support any interaction with the user. Label defines the following
constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
The first version creates a blank label. The second version creates a label that contains
the string specified by str. This string is left-justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how
must be one of these three constants: [Link], [Link], or [Link].
Using Buttons:
A push button is a component that contains a label and that generates an event when
it is pressed. Push buttons are objects of type Button. Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains
str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ActionListener
16
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]()=="Red")
setBackground(new Color(255,0,0));
if([Link]()=="Green")
setBackground(new Color(0,255,0));
if([Link]()=="Blue")
setBackground(new Color(0,0,255));
}
}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);
}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small
box that can either contain a check mark or not. There is a label associated with each check
box that describes what option the box represents. Check boxes can be used individually or
as part of a group. Check boxes are objects of the Checkbox class.
Checkbox supports these constructors:
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException
The first form creates a check box whose label is initially blank. The state of thecheck
box is unchecked. The second form creates a check box whose label is specified by [Link]
state of the check box is unchecked. The third form allows you to set the initial state of the
check box. If on is true, the check box is initially checked; otherwise, it is cleared. The fourth
and fifth forms create a check box whose label is specified by str and whose group is specified
by cbGroup. If this check box is not part of a group, then cbGroup must be null. The value of
on determines the initial state of the check box.
Methods:
boolean getState( ) - To retrieve the current state of a check box
void setState(boolean on) - to set the state of a check box
String getLabel( ) – returns the label associated with check box
void setLabel(String str) – to set the label
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
[Link]("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");
msg="Male (True/False)"+[Link]();
[Link](msg,150,200);
19
msg="Female (True/False)"+[Link]();
[Link](msg,150,250);
msg="Transzender (True/False)"+[Link]();
[Link](msg,150,300);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
[Link]("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");
add(m); add(f); add(t);
}
}
class Demo
{
public static void main(String arg[])
20
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
CheckboxGroup(RADIO BUTTON)
It is possible to create a 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 —only one button can be selected at any one time.
To create a set of mutually exclusive check boxes, you must first define the group to
which they will belong and then specify that group when you construct the check boxes. Check
box groups are objects of type CheckboxGroup.
Only the default constructor is defined, which creates an empty group.
Methods:
Checkbox getSelectedCheckbox( ) - which check box in a group is currently selected
void setSelectedCheckbox(Checkbox which) - which is the check box that you want to
be selected. The previously selected check box will be turned off
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
[Link](f);
21
add(m); add(f); add(t);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State : " +[Link]();
[Link](msg,150,150);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
[Link](f);
Choice Controls:
The Choice class is used to create a pop-up list of items from which the user may
choose. Choice defines only the default constructor, which creates an empty list. To add a
selection to the list, call add( ). It has this general form:
void add(String name) - name is the name of the item being added.
Items are added to the list in the order in which calls to add( ) occur.
Methods:
String getSelectedItem( ) – returns the item which is currently selected
int getSelectedIndex( ) - returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected.
int getItemCount( ) – returns number of items in the list
void select(int index) - to set the currently selected item with index
void select(String name) - to set the currently selected item with a string
String getItem(int index) – returns the name associated with the index
Example:
23
mport [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
Choice c;
String msg="";
MyFrame()
{
c=new Choice();
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR"); add(c);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current Selection : "+[Link]();
[Link](msg, 150,150);
}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Choice c;
MyFrame()
{
c=new Choice();
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(c);
}
}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
List:
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections.
List provides these constructors:
List( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
The first version creates a List control that allows only one item to be selected at any
one time. In the second form, the value of numRows specifies the number of entries in the list
that will always be visible (others can be scrolled into view as needed). In the third form, if
multipleSelect is true, then the user may select two or more items at a time. If it is false, then
only one item may be selected.
To add a selection to the list, call add( ). It has the following two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the
end of the list. The second form adds the item at the index specified by index. Indexing begins
at zero. You can specify –1 to add the item to the end of the list.
Example:
// Demonstrate Lists.
import [Link].*;
import [Link].*;
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
26
}
public void paint(Graphics g)
{
for(int i:[Link]())
msg+=i;
[Link](msg,150,150);
msg="";
for(String i:[Link]())
msg+=i;
[Link](msg,150,200);
}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
// Demonstrate Lists.
import [Link].*;
import [Link].*;
27
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(l);
}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
TextField:
The TextField class implements a single-line text-entry area. Text fields allow the user
to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse
selections.
TextField is a subclass of TextComponent. TextField defines the following
constructors:
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field. The second form creates a text field that
is numChars characters wide. The third form initializes the text field with the string contained
in str. The fourth form initializes a text field and sets its width.
Methods:
String getText( ) - To obtain the string currently contained in the text field
28
void setText(String str) - To set the text, here, str is the new string.
String getSelectedText( ) - returns currently selected text
void select(int startIndex, int endIndex) - selects the characters beginning at startIndex
and ending at endIndex –1.
boolean isEditable( ) – returns boolean value (true/false)
void setEditable(boolean canEdit) - if canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
void setEchoChar(char ch) – specified echo character will be displayed in TextField
boolean echoCharIsSet( ) –returns true or false
char getEchoChar( ) – returns the echo character
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements TextListener
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);
[Link](this);
}
public void textValueChanged(TextEvent te)
{
repaint();
}
public void paint(Graphics g)
{
msg="Text in the Field : "+[Link]();
[Link](msg,150,150);
msg="Text in the Field : "+[Link]();
[Link](msg,150,200);
msg="is editable:"+[Link]();
[Link]( msg ,150,250);
}
}
29
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);
}
}
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
30
{
[Link](0);
}
});
}
}
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea. Following are the
constructors for TextArea:
TextArea( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws
HeadlessException
Here, numLines specifies the height, in lines, of the text area, and numChars specifies
its width, in characters. Initial text can be specified by str. In the fifth form, you can specify
the scroll bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),
setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described
in the preceding section.
TextArea adds the following methods:
void append(String str) - appends the string specified by str to the end of the current
void insert(String str, int index) - inserts the string passed in str at the specified index
void replaceRange(String str, int startIndex, int endIndex) - replaces the characters
from startIndex to endIndex–1, with the replacement text passed in str
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextArea ta;
MyFrame()
{
ta=new TextArea("PVP Siddhartha Inst. of Technology");
add(ta);
}
}
class TextDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Scroll Bars:
Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following
constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException
The first form creates a vertical scroll bar. The second and third forms allow you to
specify the orientation of the scroll bar. If style is [Link], a vertical scroll
bar is created. If style is [Link], the scroll bar is horizontal. In the third
form of the constructor, the initial value of the scroll bar is passed in initialValue. The number
of units represented by the height of the thumb is passed in thumbSize. The minimum and
maximum values for the scroll bar are specified by min and max.
Methods:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements AdjustmentListener
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r,"South");
add(g,"East");
add(b,"North");
[Link](this);
[Link](this);
[Link](this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
setBackground(new Color([Link](),[Link](),[Link]()));
}
}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Scrollbar Programs...");
[Link](true);
[Link](new BorderLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
33
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r );
add(g);
add(b);
}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Scrollbar Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Layout Manager
A layout manager is a class that is useful to arrange components in a particular manner
in container or a frame.
Java soft people have created a LayoutManager interface in [Link] package which is
implemented in various classes which provide various types of layouts to arrange the
components. The following classes represents the layout managers in Java:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
6. BoxLayout
To set a particular layout, we should first create an object to the layout class and pass
the object to setLayout() method. For example, to set FlowLayout to the container:
34
FlowLayout obj=new FlowLayout();
c. setLayout(obj); // assume c is container
FlowLayout:
FlowLayout is useful to arrange the components in a line one after the other. When a
line is filled with components, they are automatically placed in a next line. This is the default
layout in applets.
Constructors:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centres components and leaves five
pixels of space between each component. The second form lets you specify how each line is
aligned. Valid values for how are as follows:
[Link]
[Link]
[Link]
The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
Example:
import [Link].*;
import [Link].*;
}
}
class ListDemo
{
public static void main(String arg[])
{
35
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
BorderLayout:
BorderLayout is useful to arrange the components in the four borders of the frame as
well as in the centre. The borders are identified with the names of the directions. The top border
is specified as ‗North‘, the right side border as ‗East‘, the bottom one as ‗South‘ and the left
one as ‗West‘. The centre is represented as ‗Centre‘.
Constructors:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
[Link]
[Link]
[Link]
[Link]
[Link]
When adding components, you will use these constants with the following form of
add( ), which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will
be added.
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4,b5;
36
MyFrame()
{
b1=new Button("East");
b2=new Button("West");
b3=new Button("South");
b4=new Button("North");
b5=new Button("Center");
add(b1,"East");
add(b2,"West");
add(b3,"South");
add(b4,"North");
add(b5,"Center");
}
}
class BorderDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
GridLayout:
GridLayout is useful to divide the container into a 2D grid form that contains several
rows and columns. The container is divided into equal-sized rectangle; and one component is
placed in each rectangle.
Constructors:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. The third form allows you to specify
the horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimitedlength columns. Specifying numColumns as zero allows for unlimited-length rows.
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4;
MyFrame()
{
setLayout(new GridLayout(2,2,20,20));
b1=new Button("GFGC");
b2=new Button("MGD");
b3=new Button("BU");
b4=new Button("BLR");
add(b1 );
add(b2);
add(b3);
add(b4);
}
}
class GridDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Java JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user can select a value
from a specific range.
JSlider() creates a slider with the initial value of 50 and range of 0 to 100.
JSlider(int orientation) creates a slider with the specified orientation set by either [Link]
or [Link] with the range 0 to 100 and initial value 50.
JSlider(int min, int max) creates a horizontal slider using the given min and max.
JSlider(int min, int max, int creates a horizontal slider using the given min, max and value.
value)
JSlider(int orientation, int min, creates a slider using the given orientation, min, max and value.
int max, int value)
public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider.
public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider.
public void setPaintTicks(boolean b) is used to determine whether tick marks are painted.
public void setPaintLabels(boolean b) is used to determine whether labels are painted.
Output:
Output:
Applets
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following −
An applet is a Java class that extends the [Link] class.
A main() method is not invoked on an applet, and an applet class will not define
main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
Applet Life Cycle in Java
In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five
core methods namely init(), start(), stop(), paint() and destroy().These methods are invoked
by the browser to execute.
Along with the browser, the applet also works on the client side, thus having less processing
time.
Methods of Applet Life Cycle
There are five methods of an applet life cycle, and they are:
o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
o start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from one tab to another in
the browser. It is in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage
is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Sequence of method execution when an applet is executed:
1. init()
2. start()
3. paint()
1. stop()
2. destroy()
These methods are invoked by the browser automatically. There is no need to call them
explicitly.
An input stream is used to read data from the source. And, an output stream is used to write data to
the destination.
class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
For example, in our first Hello World example, we have used [Link] to print a string. Here,
the System. Out is a type of output stream.
Input stream reads data from source to program and output stream writes file from program to
destination
Types of Streams
Depending upon the data a stream holds, it can be classified into:
Byte Stream
Character Stream
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and
OutputStream
Character Stream
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and Writer
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of
them are:
FileInputStream
ByteArrayInputStream
ObjectInputStream
// Creates an InputStream
InputStream object1 = new FileInputStream();
Methods of InputStream
The InputStream class provides different methods that are implemented by its
subclasses. Here are some of the commonly used methods:
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the
stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream
import [Link];
import [Link];
class Main {
public static void main(String args[]) {
try {
InputStream input = new FileInputStream("[Link]");
Output
Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some of
them are:
FileOutputStream
ByteArrayOutputStream
ObjectOutputStream
OutputStreamWriter
We will learn about all these subclasses in the next tutorial.
Create an OutputStream
// Creates an OutputStream
OutputStream object = new FileOutputStream();
Note: We can also create the output stream from other subclasses of
the OutputStream class.
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its
subclasses. Here are some of the methods:
write() - writes the specified byte to the output stream
write(byte[] array) - writes the bytes from the specified array to the output stream
flush() - forces to write all data present in output stream to the destination
close() - closes the output stream
import [Link];
import [Link];
public class Main {
try {
OutputStream out = new FileOutputStream("[Link]");
catch (Exception e) {
[Link]();
}
}
}
When we run the program, the [Link] file is filled with the following content.
The Reader class of the [Link] package is an abstract superclass that represents a
stream of characters.
Since Reader is an abstract class, it is not useful by itself. However, its subclasses can
be used to read data.
Subclasses of Reader
In order to use the functionality of Reader, we can use its subclasses. Some of them are:
BufferedReader
InputStreamReader
FileReader
StringReader
Subclasses of Reader
We will learn about all these subclasses in the next tutorial.
Create a Reader
In order to create a Reader, we must import the [Link] package first. Once we
import the package, here is how we can create the reader.
// Creates a Reader
Reader input = new FileReader();
Here, we have created a reader using the FileReader class. It is because Reader is an
abstract class. Hence we cannot create an object of Reader.
Methods of Reader
The Reader class provides different methods that are implemented by its subclasses.
Here are some of the commonly used methods:
ready() - checks if the reader is ready to be read
read(char[] array) - reads the characters from the stream and stores in the specified
array
read(char[] array, int start, int length) - reads the number of characters
equal to length from the stream and stores in the specified array starting from the start
mark() - marks the position in the stream up to which data has been read
reset() - returns the control to the point in the stream where the mark is set
skip() - discards the specified number of characters from the stream
import [Link];
import [Link];
class Main {
public static void main(String[] args) {
try {
// Creates a reader using the FileReader
Reader input = new FileReader("[Link]");
// Reads characters
[Link](array);
[Link]("Data in the stream:");
[Link](array);
catch(Exception e) {
[Link]();
}
}
}
Output
In the above example, we have created a reader using the FileReader class. The reader
is linked with the file [Link].
To read data from the [Link] file, we have implemented these methods.
The Writer class of the [Link] package is an abstract superclass that represents a
stream of characters.
Since Writer is an abstract class, it is not useful by itself. However, its subclasses can
be used to write data.
Subclasses of Writer
In order to use the functionality of the Writer, we can use its subclasses. Some of them
are:
BufferedWriter
OutputStreamWriter
FileWriter
StringWriter
Subclasses of Writer
We will learn about all these subclasses in the next tutorial.
Create a Writer
In order to create a Writer, we must import the [Link] package first. Once we
import the package, here is how we can create the writer.
// Creates a Writer
Writer output = new FileWriter();
Here, we have created a writer named output using the FileWriter class. It is because
the Writer is an abstract class. Hence we cannot create an object of Writer.
Note: We can also create writers from other subclasses of the Writer class.
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses.
Here are some of the methods:
write(char[] array) - writes the characters from the specified array to the output
stream
write(String data) - writes the specified string to the writer
append(char c) - inserts the specified character to the current writer
flush() - forces to write all the data present in the writer to the corresponding
destination
close() - closes the writer
Here is how we can implement the Writer using the FileWriter class.
import [Link];
import [Link];
public class Main {
try {
// Creates a Writer using FileWriter
Writer output = new FileWriter("[Link]");
catch (Exception e) {
[Link]();
}
}
}
In the above example, we have created a writer using the FileWriter class. The writer
is linked with the file [Link].
When we run the program, the [Link] file is filled with the following content.
RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached before the desired number of byte
has been read than EOFException is thrown. It is a type of IOException.
Constructor
Constructor Description
Method
Modifier Method Method
and Type
void close() It closes this random access file stream and releases
any system resources associated with the stream.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import [Link];
import [Link];
The [Link] contains text "This class is used for reading and writing to random access file."