0% found this document useful (0 votes)
6 views25 pages

Module 4.docx

The document provides an overview of Java applets, including their definition, types (local and remote), and lifecycle stages. It explains how applets differ from applications, their advantages and drawbacks, and outlines the process of writing and running applet code. Additionally, it covers event handling in Java through the delegation event model, detailing event sources, listeners, and event classes.

Uploaded by

Tanuj Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Module 4.docx

The document provides an overview of Java applets, including their definition, types (local and remote), and lifecycle stages. It explains how applets differ from applications, their advantages and drawbacks, and outlines the process of writing and running applet code. Additionally, it covers event handling in Java through the delegation event model, detailing event sources, listeners, and event classes.

Uploaded by

Tanuj Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Module 4

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

How Applets differ from Applications-


● Applets do not use the main() method for initiating the execution of the code. Applets when loaded automatically
call certain methods of Applet class to start and execute the applet code.
● Applets cannot be run independently. They are run inside a Web page using a special feature known as HTML tag.
● Applets cannot read and write to the files in the local computer.
● Applets cannot communicate with other servers on the network.
● Applets cannot run any program any from the local computer.
● Applets are restricted from using libraries from other languages such as C or C++.

Why to use Applet?-


● When we need to include something dynamic to include in our page.
● When we require some flash output like applet to produce sound, animations or some special effects.
● When we want to create a program and want it to make available on internet so that it could be used by others.

Life Cycle of an Applet-


Every Java Applet has a life cycle through which it passes throughout his life span. Every Java Applet inherits the behavior
from the Applet Class. Applet Life contains the following states-
1. Born or Initialization State
2. Running State
3. Idle State
4. Dead or Destroyed State
Begin Initialization

start()
stop()
Display
paint() start() Stopped

destroy()

Destroyed End

An Applet State Transition Diagram

1. Born or Initialization State-


Applet enters the initialization state when it is loaded. This is achieved by calling the init() method of Applet class. At this
stage we may do the following if required-
1. Create objects needed by the applet
2. Set up the initial values
3. Load Images or fonts
4. Set up colors
The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors mentioned above, we
must override the init() method:
public void init(){
Action
}

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
}

Idle or Stopped State-


An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page
containing the currently running applet. We can also do by calling the stop() method explicitly. If we use a thread to run
an applet, then we must use stop() method to terminate the thread. We can achieve this by override the stop() method:
public void stop(){
Action
}
Dead State-
An applet is said to be dead when it is removed from memory. This occurs automatically by invoking destroy() method
when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If an applet has
created any resources, like threads we may override the destroy() method to clean up the resources.
public void destroy(){
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
}

Writing Applet Code-


Before we try to write applet, we must make sure that Java is installed properly and also ensure that either the Java
Applet Viewer or a Java enabled browser is available. The steps involved in developing and testing in applet are-
1. Building an Applet Code (.java file)
2. Creating an Executable Applet (.class file)
3. Designing a Web Page using HTML tags
4. Preparing <APPLET> tag
5. Incorporating < APPLET> tag into the Web page
6. Running the Applet

1. Building an Applet Code-


In order to create an applet tag we have to use two classes namely Applet and Graphics from the Java Class Library. The
Applet class which is contained in the java.applet package provides life and behavior to the applet through its methods
such as init(), start() and paint(). Unlike application in which the execution starts from main() function, in applet Java
automatically calls a series of Applet class methods for running and stopping the applet code when Applet is loaded. The
Applet class therefore maintains the lifecycle of an applet.
The paint() method of an Applet class, when it is called, displays the result of the applet code on the screen. The
output may be text, graphics or sound. The paint method requires a Graphics object as an argument.
public void paint(Graphics g)
This requires that the applet code imports the java.awt package that contains the Graphics class.

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.

2. Creating an Executable Applet-


Now after typing the code, you have to save the file with any name with an extension .java and right after that you to
convert the .java file to executable file i.e., .class file.
Let us consider the HelloJava applet was created in the first step. This applet has been stored in a file called
HelloJava.java. Then the steps required for compiling the Applet are:
● Move to the directory containing the source code and type the following command:
Javac HelloJava.java
● The compiled output file called HelloJava.class is placed in the same directory as the source.
● If any error message is received, then we must check for errors, correct them and compile the applet again.

3. Designing a Web Page-


A web page is a HTML page which include both text that we want to display and HTML tags to web browsers. A web page
is marked by an opening HTML tag <HTML> and a closing HTML tag </HTML>. It is divided in the three major sections:
● Comment Section- This section contains Comments. It is important to include comments that tell us what is going on
in the Web page. A comment line begins with a <! And ends with a>.
● Head Section- This section usually contains a title of the Web Page as shown below:
<HEAD>
<TITLE>My Applet</TITLE>
</HEAD>
● Body Section- We call this as body section because this section contains the entire information about the Web Page
and its behavior.
<BODY>
<CENTER>
<H1>Welcome to the world of Applets</H1>
</CENTER>
<BR>
<APPLET......></APPLET>
</BODY>

4. Preparing <APPLET> tag-


The <APPLET....>tag supplies the name of the applet to be loaded and tells the browser how much space applet requires.
The .... in the tag indicates that it contains certain attributes that must be specified. The <APPLET> tag given below
specifies the minimum requirements to place the HelloJava applet on the applet:
<APPLET CODE=HelloJava.class WIDTH=400 HEIGHT= 200>
</APPLET>

5. Incorporating < APPLET> tag into the Web page-


<HTML>
<! This page includes an APPLET Code>
<HEAD>
<TITLE>My Applet</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>Welcome to the world of Applets</H1>
</CENTER>
<BR>
<APPLET CODE=HelloJava.class WIDTH=400 HEIGHT= 200>
</APPLET>
</BODY>
</HTML>

6. Running the Applet-


Now that we have created applet files as well as the HTML file containing the applet, we must have the following:
HelloJava.java
HelloJava.class
HelloJava.html
To run an applet, we requires one of the following tools:
● Java-enabled Web Browser (such as HotJava or Netscape)
● Java appletviewer
If we use a Java-enabled Web Browser, we will be able to see the entire Web Page containing the applet.
If we use the appletviewer tool, we will only see the applet output. The appletviewer is available as a part of Java
Development Kit that we have been using so far. We can use it to run our applet as follows:
appletviewer HelloJava.html

Passing Parameters to Applets-


We can supply user-defined parameters to an applet using <PARAM..> tags. Each <PARAM..> tag has a name attribute
such as color, and a value attribute.
<APPLET>
<PARAM= color VALUE=”red”>
</APPLET>
Parameters are passed on an applet when it is loaded. We can define the init() method in the applet to get hold of the
parameters defined in the <PARAM> tags. This is done using the getParameter() method which takes one string argument
representing the name of the parameter and returns a string containing the value of that parameter.

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

The Delegation Event Model-


The modern approach to handling events is based on the delegation event model, which defines standard and consistent
mechanisms to generate and process events. 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-
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( )

As expected, toString( ) returns the string equivalent of the event.


The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass (either
directly or indirectly) of all AWT-based events used by the delegation event model.

Event Class Description


ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract superclass for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is made or a
checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when
the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved.
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent. Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

Event Listener Interfaces-


As explained, the delegation event model has two parts: sources and listeners. Listeners are created by implementing
one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes
the appropriate method defined by the listener and provides an event object as its argument.

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)

Using the Delegation Event Model-


Using the delegation event model is actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.

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.

Java AWT Hierarchy-


The hierarchy of Java AWT classes are given below.
AWT Hierarchy
Components-
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for
each component as shown in above diagram. In order to place every component in a particular position on a screen, we
need to add them to a container.

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.

Working with Frame Windows-


After the applet, the type of window you will most often create is derived from Frame. You will use it to create child
windows within applets, and top-level or child windows for stand-alone applications. As mentioned, it creates a
standard-style window.
Here are two of Frame’s constructors:
Frame( )
Frame(String title)

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.

Setting the Window’s Dimensions-


setSize()- The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)

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.

Hiding and Showing a Window-


setVisible( )- After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is
shown here:
void setVisible(boolean visibleFlag)
The component is visible if the argument to this method is true. Otherwise, it is hidden.

Setting a Window’s Title-


setTitle()- You can change the title in a frame window using setTitle( ), which has this general form:
void setTitle(String newTitle)
Here, newTitle is the new title for the window. Closing a Frame Window

Closing a Frame Window-


When using a frame window, your program must remove that window from the screen when it is closed, by calling
setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the
WindowListener interface. Inside windowClosing( ), you must remove the window from the screen. The example in the
next section illustrates this technique.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the
Frame.

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

AWT Example by Association

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

1. setColor()- This method is used to set the drawing color.


● public Color(int r, int g, int b)- Creates a color based on the value of Red, Green and Blue components expressed as
integers between 0 to 255.
Example-
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet {
Color obj= new Color(255, 52, 153);
public void paint(Graphics g){
g.setColor(obj);
g.drawString(“Applet World”, 20,80);
}
}
Output-
Applet World // In The Color Code Given
● public Color(float r, float g, float b)- Creates a color based on the value of Red, Green and Blue components
expressed as floating point values from 0.0 to 1.0.
● public void setColor(Color obj)- Sets the current color for drawing with the graphic context.
Ex- setColor(obj);
Ex- setColor(Color.red);
Example-
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet {
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString(“Applet World”, 20,80);
}
}
Output-
Applet World //Red Color

2. getColor()- This method is used to retrieve the current drawing color.


● public Color getColor()- Returns the color object representing the current color for the graphics context.
Example-
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet {
Color obj= new Color(255, 52, 153);
public void paint(Graphics g){
g.setColor(obj);
g.drawString(“Applet World”, 20,80);
g.drawString(“Color Details: “+g.getColor(), 30, 150);
}
}
Output-
Applet World
Color Details: java.awt.Color[r=255,g=52,b=153]

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.

Difference between AWT and Swing-


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

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.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.

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 Swing Examples


There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main()
method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame


f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

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

Modifier and Method Description


Type

Void setActionMap(ActionMap am) It sets the ActionMap to am.

Void setBackground(Color bg) It sets the background color of this component.

Void setFont(Font font) It sets the font for this component.

Void setMaximumSize(Dimension It sets the maximum size of this component to a constant


maximumSize) value.

Void setMinimumSize(Dimension It sets the minimum size of this component to a constant


minimumSize) value.

protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this component.

Void setVisible(boolean aFlag) It makes the component visible or invisible.

Void setForeground(Color fg) It sets the foreground color of this component.


String getToolTipText(MouseEvent It returns the string to be used as the tooltip for event.
event)

Container getTopLevelAncestor() It returns the top-level ancestor of this component (either


the containing Window or Applet), or null if this component
has not been added to any container.

TransferHandler getTransferHandler() It gets the transferHandler property.

Java JComponent Example


import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyJComponent extends JComponent {
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // add the JComponent to main frame
frame.add(com);
frame.setVisible(true);
}
}
Output-
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The application
result in some action when the button is pushed. It inherits AbstractButton class.

JButton class declaration


public class JButton extends AbstractButton implements Accessible

Java JButton Example


import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output-

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.

JLabel class declaration


public class JLabel extends JComponent implements SwingConstants, Accessible

Java JLabel Example


import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output-

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

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

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

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


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

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.

Example of FlowLayout class

import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

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.

Example of BoxLayout class with Y-AXIS:

import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));


setSize(400,400);
setVisible(true);
}

public static void main(String args[]){


BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

You might also like