Module 4.docx
Module 4.docx
Applet
Applets are the small Java programs that are primarily used in Internet Computing. They can be transported over the
Internet from one computer to another and run using the Applet Viewer or any Web Browser that supports Java.
It can perform arithmetic operations, display graphics, play sounds, accept user input, create animations and play
interactive games.
Java has enabled interactive multimedia web documents. A web page now contains not only a simple text or static image
but also a java applet which can produce graphics, sounds and moving images. Java applets therefore have begun to
make a significant impact on the www.
Local Applet-
An applet developed locally and stored in a local system is known as local applet. When a web page is trying to find a
local applet, it does not need to use internet and therefore the local system does not require the internet connection. It
simply searches the directories in the local system and locates and loads the specified applet.
Remote Applet-
A remote applet is that which is developed by someone else and stored on a remote computer connected to the
internet. If our system is connected to the internet, we can download the remote applet onto our system via the internet
and run it. In order to load a remote applet, we must know the applet’s i.e., URL(Uniform Resource Locator).
start()
stop()
Display
paint() start() Stopped
destroy()
Destroyed End
Running State-
Applet enters the running state when the system calls the start() of Applet class. This occurs automatically after the
applet is initialized. Starting can also occur if the applet is already in idle state.
Suppose we leave the web page containing the applet temporarily to another page and return back to the page. This
again starts the applet running. Note that unlike init() method, the start() method may be called more than once.
public void start(){
Action
}
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 the running state. The paint() method is called to accomplish this task. Almost every
applet will have a paint() method. Like other methods in the life cycle the default version of paint() method does nothing.
We must therefore override this method if we want anything to be displayed on the screen.
public void paint(Graphics g){
Display Statements
}
Structure-
import java.awt.*;
import java.applet.*;
...........
public class appletclassname extends Applet {
................
public void paint(Graphics g){
Applet Operations Code
}
..............................
}
Example-
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet {
public void paint(Graphics g){
g.drawString(“Hello Java”, 10, 100);
}
}
Here drawString is used to print a message with 10 pixels on x axis and 100 pixels on the y axis. That means drawString
takes the argument i.e., the value to be printed with two axis as x and y axis.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet
Event Handling
Events-
In the delegation model, 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 graphical user interface. 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. This occurs when the internal state of that object changes in some way.
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)
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. First, it must have been
registered with one or more sources to receive notifications about specific types of events. Second, 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 java.awt.event.
Event Classes-
The classes that represent events are at the core of Java’s event handling mechanism.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events.
Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the
event. Its general form is shown here:
Object getSource( )
Interface Description
ActionListener Defines one method to receive action events.
void actionPerformed(ActionEvent ae)
AdjustmentListener Defines one method to receive adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Defines four methods to recognize when a component is hidden, moved, resized, or shown.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Defines two methods to recognize when a component is added to or removed from a container.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
FocusListener Defines two methods to recognize when a component gains or loses keyboard focus.
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemListener Defines one method to recognize when the state of an item changes.
void itemStateChanged(ItemEvent ie)
KeyListener Defines three methods to recognize when a key is pressed, released, or typed.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Defines five methods to recognize when the mouse is clicked, enters a component, exits a
component, is pressed, or is released.
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
void mouseWheelMoved(MouseWheelEvent mwe)
TextListener Defines one method to recognize when a text value changes.
void textChanged(TextEvent te)
WindowFocusListener Defines two methods to recognize when a window gains or loses input focus.
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Defines seven methods to recognize when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Adapter Classes
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. You can define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ), which
are the methods defined by the MouseMotionListener interface. If you were interested in only mouse drag events, then
you could simply extend MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you. Table 22-4 lists the commonly used adapter classes in
java.awt.
AWT Package
The Abstract Window Toolkit (AWT) package in Java enables the programmers to create GUI based applications. It
contains a number of classes that help to implement common Window based tasks, such as manipulating windows,
adding scroll bars, buttons, list items, text boxes etc. All the classes are contained in the java. awt package. These classes
are hierarchically arranged inside the awt package in such a manner that each successive level in the hierarchy adds
certain attributes to the GUI application.
AWT Classes-
The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. Fortunately, because it is
logically organized in a top-down, hierarchical fashion, it is easier to understand and use than you might at first believe.
Some of the commonly used AWT Classes are-
Class Description
Button Creates a push button control.
Canvas A blank, semantics-free window.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Color Manages colors in a portable, platform-independent fashion.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Font Encapsulates a type font.
FontMetrics Encapsulates various information related to a font. This information helps you display text in a
window.
Frame Creates a standard window that has a title bar, resize corners, and a menu bar.
Graphics Encapsulates the graphics context. This context is used by the various output methods to display
output in a window.
Image Encapsulates graphical images.
Label Creates a label that displays a string.
List Creates a list from which the user can choose. Similar to the standard Windows list box.
Menu Creates a pull-down menu.
MenuBar Creates a menu bar.
MenuComponent An abstract class implemented by various menu classes.
MenuItem Creates a menu item.
Panel The simplest concrete subclass of Container.
Scrollbar Creates a scroll bar control.
TextArea Creates a multiline edit control.
TextComponent A superclass for TextArea and TextField.
TextField Creates a single-line edit control.
Window Creates a window with no frame, no menu bar, and no title.
Container-
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The
classes that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains and
controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window-
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for
creating a window. We need to create an instance of Window class to create this container.
Panel-
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the
components. It can have other components like button, text field etc. An instance of Panel class creates a container, in
which we can add components.
Frame-
The Frame is the container that contain title bar and border and can have menu bars. It can have other components like
button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application.
The first form creates a standard window that does not contain a title. The second form creates a window with
the title specified by title. Notice that you cannot specify the dimensions of the window. Instead, you must set the size of
the window after it has been created.
The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension
object passed in newSize. The dimensions are specified in terms of pixels.
getSize()- The getSize( ) method is used to obtain the current size of a window. Its signature is shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width and height fields of a Dimension object.
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}
}
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button
component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}
}
Graphics Class-
Java’s Graphics Class include methods for drawing many different types of shapes , from simple lines to polygons to text
in a variety of fonts.
Some commonly used drawing methods in the Graphics class are-
Method Description
clearRect() Erases a rectangular area of the canvas
copyArea() Copies a rectangular area of the canvas to another area
drawArc() Draw an hollow arc
drawLine() Draw a straight line
drawOval() Draw a hollow oval
drawPolygon() Draw a hollow polygon
drawRect() Draw a hollow rectangle
drawRoundRect() Draw a hollow rectangle with rounded corners
drawString() Displays a text string
fillArc() Draw an filled arc
fillOval() Draw a filled oval
fillPolygon() Draw a filled polygon
fillRect() Draw a filled rectangle
fillRoundRect() Draw a filled rectangle with rounded corners
getColor() Retrieves the current drawing color
getFont() Retrieves the current used font
getFontMetrics() Retrieves information about the current font
setColor() Sets the drawing color
setFont() Sets the font
Color Class-
This class have two methods –
1. setColor()
2. getColor()
Font Class-
This Class has two methods-
1. setFont()
2. getFont()
1. setFont()-
● public Font(Font name, Font style, Font size)
Font Name- “Times New Roman”
Font Style-Font.ITALIC/ Font.BOLD/ Font. PLAIN
Font Size-20
Ex- Font obj= new Font(“Times New Roman”, Font.BOLD, 20);
● public void setFont(Font obj)- Sets the current font, style and size specified by the Font Object Reference obj.
Ex- setFont(obj);
Ex- setFont(new Font(“Times New Roman”, Font.BOLD, 20));
Example-
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet {
Font obj= new Font(“Times New Roman”, Font.BOLD, 40);
public void paint(Graphics g){
g.setFont(obj);
g.drawString(“Applet World”, 20,80);
}
}
Output-
Applet World //in Times Roman, Bold and size=40
2. getFont()-
● public Font getFont()- Returns a Font object reference representing the current font.
Example-
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet {
Font obj= new Font(“Times New Roman”, Font.Bold, 40);
public void paint(Graphics g){
g.setFont(obj);
g.drawString(“Applet World”, 20,80);
g.drawString(“Font Details:” +g.getFont(), 30,200);
}
}
Output-
Applet World // in Times Roman, Bold and size=40
Font Details: java.awt.Font[family=Times New Roman, name=Times New Roman, style=bold, size=40]
● It has some attributes-
getName()- Returns only the Name of the Font Used
getStyle()- Returns the integer value of the Style Used Ex- Italic =2
getSize()- Returns the size of the Font
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the
top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton,
JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane
etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Java JComponent
The JComponent class is the base class of all Swing components except top-level containers. Swing components whose
names begin with "J" are descendants of the JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But,
JFrame and JDialog don't inherit JComponent class because they are the child of top-level containers.
The JComponent class extends the Container class which itself extends Component. The Container class has support for
adding components to the container.
Useful Methods
protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this component.
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text.
The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
Java LayoutManagers
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. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
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. The BorderLayout provides five
constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between
the components.
Example of BorderLayout class:
import java.awt.*;
import javax.swing.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between
the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns
alongwith given horizontal and vertical gaps.
Example of GridLayout class
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of
applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical
gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal
and vertical gap.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides
four constants. They are as follows:
Note: BoxLayout class is found in javax.swing package.
Fields of BoxLayout class
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Constructor of BoxLayout class
1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
import java.awt.*;
import javax.swing.*;