0% found this document useful (0 votes)
14 views

CH-5 Java_notes.

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CH-5 Java_notes.

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Ch-5 Java Applets and Graphics Programming Marks: 10

Applet

 Applet is java program that can be embedded into html pages.


 Applets transported over the internet form one computer to another and
run using applet viewer or can run on any java enabled web browser using
JVM.
OR
 An applet is a small program that is intended not to be run on its own, but
rather to be embedded inside another application. The applet class
provides a standard interface between applet and their environment.

Advantages of applet
 It provides GUI, facilitates graphics animation and multimedia.
 Avoids risk and provide 2 way interactions between webpages.
 Applets can work on all versions of Java plugin.

disadvantages of applet

 Java applets requires JVM so first time it takes significant startup time.
 It is difficult to design and build good user interface in applet as compare to
html technology.
 Some organization only allowed software installed by administrator, As a
result many users cannot view applet by default.

Types of Applets
1. Local Applets

 An applet developed locally and stored in a local system is known as a local


applet.
 When a web page is trying to find a local applet, it does not need to use the
internet and therefore the local system does not require the internet
connection. It simply searches the directories in the local system; locates
and loads the specified applet.

Page 1
 A local applet is specified by a path name and a file name.

 For e.g. <applet


code="JPR.class"
width=120
height=120>
</applet>

2. 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 into our
system via at the internet and run it.
 Your browser must, of course, be connected to the Internet at the time it
needs to display the remote applet.
 For locate and load a remote applet, we must know the applet’s address on
the web. This address is known as Uniform Resource Location (URL).

 For e.g.
<applet
codebase="http://www.vpt.edu.in/applets/"
code="JPR.class"
width=120

Page 2
height=120>

Applet Application
Applet does not use main() method Application use main() method for
for initiating execution of code initiating execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to Application can read from or write
files in local computer to files in local computer
Applet cannot communicate with Application can communicate with
other servers on network other servers on network
Applet cannot run any program Application can run any program
from local computer. from local computer.
Applet are restricted from using Application are not restricted from
libraries from other language such using libraries from other language
as C or C++
Applets are event driven. Applications are control driven.

Page 3
Life Cycle of Applet

Page 4
 Applet Life Cycle: An Applet has a life cycle, which describes how it
starts, how it operates and how it ends. The life cycle consists of four
methods:
1. init()
2. start()
3. stop()
4. destroy().
1. Initialization State (The init() method):
 The life cycle of an Applet is begin on that time when the applet is first
loaded into the browser and called the init() method.
 The init() method is called only one time in the life cycle on an Applet.
The init() method is basically called to read the “PARAM” tag in the html
file.
 The init () method retrieve the passed parameter through the “PARAM”
tag of html file using get Parameter() method All the initialization such
as initialization of variables and the objects like image, sound file are
loaded in the init () method.
 After the initialization of the init() method user can interact with the
Applet and mostly applet contains the init() method.
 Syntax:
public void init()
{
----
----
}

2. Running State (The start() method):


 The start method of an Applet is called after the initialization method init().
This method may be called multiples time when the Applet needs to be
started or restarted.
 For Example if the user wants to return to the Applet, in this situation the
start() method of an Applet will be called by the web browser and the user
will be back on the applet. In the start method user can interact within the
applet.

Page 5
 Syntax:- public void start()
{
……..
……..
}
3. Idle (The Stop() method):
 An applet becomes idle when it is stopped from running. The stop() method
stops the applet and makes it invisible.
 Stopping occurs automatically when we leave the page containing the
currently running applet. We can also do so by calling the stop() method
explicitly.
 The stop() method can be called multiple times in the life cycle of applet
like the start () method or should be called at least one time.
 For example the stop() method is called by the web browser on that time
When the user leaves one applet to go another applet and the start()
method is called on that time when the user wants to go back into the first
program or Applet.
 Syntax:- public void stop()
{
……..
……..
}
4. Dead State (The destroy() method):
 The destroy() method is called to terminate an Applet. an Applet is said to
be dead when it is removed from memory.
 This occurs automatically by invoking the destroy() method when we quit
the browser. It is useful for clean-up actions, such as releasing memory
after the applet is removed, killing off threads and closing
network/database connections.
 Thus this method releases all the resources that were initialized during an
applet’s initialization.
 Syntax:-public void destroy()
{
……..

Page 6
……..
}

5. Display State (The paint() method):


 The paint() method is used for applet display on the screen. The display
includes text, images, graphics and background.
 This happens immediately after the applet enters into the running state.
Almost every applet will have a paint() method and can be called several
times during an applet’s life cycle.
 The paint() method is called whenever a window is required to paint or
repaint the applet.
 Syntax:-public void paint(Graphics g)
{
……..
……..
}

The repaint method in java is available in java.applet.Applet class is a final

method used whenever we want to call update method along with the call to

paint method; call to update method clears the current window, performs an

update, and afterwards calls paint method.

Syntax:

package <packagename>;

// class extending applet

public class <classname> extends Applet{

public method <methodName>(<arguments>){

repaint(); // calling repaint method when required

Page 7
The above syntax shows how a repaint method is used in java. The repaint

method is a part of the java.applet.Applet class, and it cannot be overridden.

Therefore repaint method can be directly called from a class extending Applet or

its subclasses.

How does repaint work in Java?


The repaint method is a final method available in the Applet class, and that’s why

it cannot be overridden. Whenever the repaint method is to be used, it should be

directly called from the Applet class’s subclasses. The repaint method is

responsible for handling update to the paint cycle of the applet. Whenever we

want a component to repaint itself, we need to call the repaint method. In case

we have made changes to the appearance of a component but have not made

any changes to its size, then we can call the repaint method to update the new

appearance of the component on the graphical user interface. The repaint

method is an asynchronous method of applet class. When call to repaint method

is made, it performs a request to erase and perform redraw of the component

after a small delay in time.

Whenever the repaint method is invoked from a component, a request is sent to

the graphical user interface, which communicates to the graphical user interface

to perform some action at a future instance of time. The whole idea behind the

repaint method is to avoid the call to paint () method directly.

Example:

import java.applet.Applet;
import java.awt.Graphics;
/*<applet code=repaint_java.class width=300 height=300></applet>*/
public class repaint_java extends Applet {

int i;
public void paint(Graphics g)
{
g.drawString("i = "+i, 100, 100);
try{

Page 8
Thread.sleep(1000);
}catch(InterruptedException ex){}
i++;
repaint();
}
}

Write a simple applet which display message ‘Welcome to Java’.

Program:
/*<applet code= WelcomeJava width= 300 height=300>
</applet>*/
import java. applet.*;
import java.awt.*;
public class WelcomeJava extends Applet
{
public void paint( Graphics g)
{
g.drawString(“Welcome to java”,25,50);
}
}

Applet Skeleton

Page 9
1.1.1 An Applet Skeleton

Most applets override these four methods. These four methods


forms Applet lifecycle.
 init() : init() is the first method to be called. This is where
variable are initialized. This method is called only once
during the runtime of applet.
 start() : start() method is called after init(). This method is
called to restart an applet after it has been stopped.
 stop() : stop() method is called to suspend thread that does
not need to run when applet is not visible.
 destroy() : destroy() method is called when your applet
needs to be removed completely from memory.
Note: The stop() method is always called before destroy()
method.
Example:
import java.awt.*;
import java.applet.*;
public class MyApplet1 extends Applet
{
public void init()
{
System.out.println("Applet initialized");
}
public void start()
{
System.out.println("Applet execution started");
}
public void stop()
{
System.out.println("Applet execution stopped");
}
public void paint(Graphics g)
{
System.out.println("Painting...");
Page 10
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
/*<applet code=MyApplet1.class height=200 width=200></applet>*/

When user close that applet window, then output is like this:

Adding Applet to the HTML file

Steps to add an applet in HTML document

Page 11
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the
body
section of HTML file.
2. Specify the name of the applet’s .class file.
3. If the .class file is not in the current directory then use the codebase
parameter to
specify:-
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is
on
a remote computer.
4. Specify the space required for display of the applet in terms of width and
height in
pixels.
5. Add any user-defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non-java browser is used.
7. Close the applet declaration with the </APPLET> tag.

Open notepad and type the following source code and save it into file name
“Hellojava.java”

import java.awt.*;
import java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello Java",10,100);
}
}

Use the java compiler to compile the applet “Hellojava.java” file.


C:\jdk> javac Hellojava.java

Page 12
After compilation “Hellojava.class” file will be created. Executable applet is
nothing but the .class file of the applet, which is obtained by compiling the source
code of the applet. If any error message is received, then check the errors,
correct them and compile the applet again.

We must have the following files in our current directory.


o Hellojava.java
o Hellojava.class
o HelloJava.html
If we use a java enabled web browser, we will be able to see the entire web page
containing the applet.
We have included a pair of <APPLET..> and </APPLET> tags in the HTML body
section. The <APPLET…> tag supplies the name of the applet to be loaded and
tells the browser how much space the applet requires. The <APPLET> tag given
below specifies the minimum requirements to place the HelloJava applet on a
web page. The display area for the applet output as 300 pixels width and 200
pixels height. CENTER tags are used to display area in the center of the screen.
<APPLET CODE = hellojava.class WIDTH = 400 HEIGHT = 200 >
</APPLET>

Example: Adding applet to HTML file:


Create Hellojava.html file with following code:
<HTML>
<! This page includes welcome title in the title bar and displays a welcome
message. Then it specifies the applet to be loaded and executed.
>
<HEAD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
<BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER>
<BR>
<CENTER>
<APPLET CODE=HelloJava.class WIDTH = 400 HEIGHT = 200 >
</APPLET>
</CENTER>

Page 13
</BODY>
</HTML>

<PARAM> Tag or passing parameters to applet


User-define Parameter can be applied in applet using <PARAM…> tags.
Each <PARAM…> tag has a name and value attribute.
Syntax: <PARAM name = ……… Value = “………” >
In an applet code, applet can refer to a parameter by its name and then find its
value.
The two most important thing to handle and set up the parameter is the
<PARAM> tag in the HTML document and an applet code to parse this
parameter.
init() method is used to get hold of the parameters which is defined in the
<PARAM> tags. And getParameter() method is used for getting the parameters.
In Applet, Parameters are passed on applet when it is loaded.

1 Example:

param.java
import java.applet.*;
import java.awt.*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = " Welcome to Java applet ";
str = "Hello " + str;
}
public void paint(Graphics g)
{
g.drawString(str, 200, 200);
}
}

param.html
<html>
<applet code=param.class height=300 width=300>
<param Name="pname" value="Welcome to Java applet">
</applet>
</html>

2 Example:

Page 14
 User need to write java source code.
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str; public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
 User need to write html code now
<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>

Attributed of Applet tags

The HTML APPLET Tag and attributes


The APPLET tag is used to start an applet from both an HTML document and from
an applet viewer.

The syntax for the standard APPLET tag:


< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]

Page 15
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]>
[< PARAM NAME = AttributeNameVALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>

 CODEBASE is an optional attribute that specifies the base URL of the


applet code or the directory that will be searched for the applet‟s
executable class file.
 CODE is a required attribute that give the name of the file containing your
applet‟s compiled class file which will be run by web browser or
appletviewer.
 ALT: Alternate Text. The ALT tag is an optional attribute used to specify a
short text message that should be displayed if the browser cannot run java
applets.
 NAME is an optional attribute used to specifies a name for the applet
instance.
 WIDTH AND HEIGHT are required attributes that give the size(in pixels) of
the applet display area.
 ALIGN is an optional attribute that specifies the alignment of the applet.
 The possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE,
TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
 VSPACE AND HSPACE attributes are optional, VSPACE specifies the
space, in pixels, about and below the applet. HSPACE VSPACE specifies the
space, in pixels, on each side of the applet
 PARAM NAME AND VALUE: The PARAM tag allows you to specifies
applet- specific arguments in an HTML page applets access there attributes
with the get Parameter()method.

Graphics programming, Class and Methods

Page 16
 Java graphics class includes methods for drawing many different types of
shapes, from simple line to polygon to text in variety of form.
 Graphics is class present in java.awt package in which is used to perform
all the graphical operation in applet window.
 There are different methods available in graph class which are explain as
follows:
___________________________________________________________________
1. Display Text:-
drawString() method is used to display the string in an applet window
Syntax: void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example: g.drawString(“WELCOME”, 10, 10);
2. drawOval( )
Drawing Ellipses and circles: To draw an Ellipses or circles used drawOval()
method can be used.
Syntax: void drawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is
specified by top and left and whose width and height are specified by width
and height to draw a circle or filled circle, specify the same width and
height the following program draws several ellipses and circle.
Example: g.drawOval(10,10,50,50);
To draw filled oval use the method g.fillOval(30,140,70,40)
3. drawPolygon()
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], int numPoints)
The polygon‟s end points are specified by the co-ordinates pairs contained
within the x and y arrays. The number of points define by x and y is
specified by numPoints.
Example:
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);

Page 17
To draw filled polygon fillPolygon() is used.
4. drawArc( )
It is used to draw arc.
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int
sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle
is starting angle of arc sweep_angle is degree around the arc
Example: g.drawArc(10, 10, 30, 40, 40, 90);
5. drawRect()
The drawRect() method display an outlined rectangle.
Syntax: void drawRect(int top,int left,int width,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of
the Rectangle is specified by width and height.
Example: g.drawRect(10,10,60,50);
To draw filled rectangle fillRect() is used.
6. drawLine()
The drawLine() method is used to draw line which take two pair of
coordinates, (x1,y1) and (x2,y2) as arguments and draws a line between
them. The graphics object g is passed to paint() method.
Syntax: g.drawLine(x1,y1,x2,y2);
Example: g.drawLine(100,100,300,300;)
7. drawRoundRect()
This methods draws rounded rectangle, it takes 6 parameters first 4 is sane
as drawRect()and last are x diameter and y diameter.
Syntax:- g.drawRoundRect(int x, int y, int width, int height, int Xdiameter,
int ydiameter);
Example: g.drawRoundRect(30,140,70,40,10,10)
To draw filled rounded rectangle use the method
g.fillRoundrect(30,140,70,40,10,10)
8. Setting Color:
Used to set color for graphics.
Syntax: g.setColor(Color.red);
9. Creating font object and Setting font
Syntax:- Font(String FontName, String FontStyle, int FontSize)
Page 18
Example:-a=(“Times New Romen”, Font.BOLD+Font.ITALIC, 14)

Font Class

 The Font class states fonts, which are used to render text in a visible way.
 It is used to set or retrieve the screen font.

Methods Description
String getFamily( ) Returns the name of the font family to
which the invoking font belongs.
static Font getFont(String Returns the font associated with the system
property) property specified by property. null is
returned if property does not exist.
String getFontName() Returns the face name of the invoking font.
String getName( ) Returns the logical name of the invoking
font.
int getSize( ) Returns the size, in points, of the invoking
font.
int getStyle( ) Returns the style values of the invoking
font.
int hashCode( ) Returns the hash code associated with the
invoking object.
boolean isBold( ) Returns true if the font includes the BOLD
style value. Otherwise, false is returned.
boolean isItalic( ) Returns true if the font includes the ITALIC
style value. Otherwise, false is returned.
boolean isPlain( ) Returns true if the font includes the PLAIN
style value. Otherwise, false is returned.

Example:
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{

Page 19
Font f,f1;
String s,msg;
String fname;
String ffamily;
int size;
int style;
public void init()
{
f= new Font("times new roman",Font.ITALIC,20);
setFont(f);
msg="is interesting";
s="java programming";
fname=f.getFontName();
ffamily=f.getFamily();
size=f.getSize();
style=f.getStyle();
String f1=f.getName();
}
public void paint(Graphics g)
{
g.drawString("font name"+fname,60,44);
g.drawString("font family"+ffamily,60,77);
g.drawString("font size "+size,60,99);
g.drawString("fontstyle "+style,60,150);
g.drawString("fontname "+f1,60,190);
}
}
/*<applet code=Shapes.class height=300 width=300></applet>*/
Output:

Page 20
Q. Write a simple applet program which display tree concentric circle.
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.drawString("Concentric Circle",120,20);
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:

Q. Design an Applet program which displays a rectangle filled with red


color and message as “Hello Third year Students” in blue color.

Page 21
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,60,40,30);
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:

Q. Write a program to design an applet to display three circles filled


with three different colors on screen.

import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);

Page 22
g.fillOval(50,250,100,100);
}
}
/*<applet code="Shapes.class" height=300 width=200> </applet>*/
Output:

Q. Write an applet to accept a user name in the form of parameter and


print „Hello<User Name>‟.

import java.lang.*;
import java.awt.*;
import java.applet.*;
public class Hello extends Applet
{
String message;
public void init()
{
message=getParameter("username");
message="Hello" + message;
}
public void paint(Graphics g)
{
g.drawString(message, 100,100);
}
}
/*<applet code=Hello.class height=300 width=300>

Page 23
<param name="username" value="Abc">
</applet> */

Q. Design an applet which display a triangle filled with red colour and a
message as “The triangle” in blue below it.

import java.awt.*;
import java.applet.*;
public class DrawTriangle extends Applet
{
public void paint(Graphics g)
{
int xPoints[] = { 10, 170, 80, 10 };
int yPoints[] = { 20, 40, 140, 20 };
int nPoints = xPoints.length;
g.set Color(Color.red);
g.fillPolygon(xPoints, yPoints, nPoints);
g.setColor(Color.blue);
g.drawString("The triangle",50,160);
}
}
/* <applet code="DrawTriangle.class" width="350" height="300">
</applet> */
Output:

Page 24
Q. Write a program to draw a bar chart for plotting students passing
percentage in last 5 years.

Consider the following data


Year 2001 2002 2003 2004
% result of 96 85 70 98
subject
import java.awt.*;
import java.applet.*;
public class barChart extends Applet
{
String label[];
int values[];
int n=0;
public void init()
{
try
{
n=Integer.parseInt(getParameter("cols"));
label=new String[n];
values=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
values[0]=Integer.parseInt(getParameter("values1"));
values[1]=Integer.parseInt(getParameter("values2"));
values[2]=Integer.parseInt(getParameter("values3"));
values[3]=Integer.parseInt(getParameter("values4"));
}
catch(NumberFormatException e){ }
}
public void paint(Graphics g)
{

Page 25
g.setColor(Color.red);
for(int i=0;i<n;i++)
{
g.drawString(label[i],100,100+i*50);
g.fillRect(150,80+i*50,values[i],40);
}
}
}
Code for html file
<html>
<applet code="barChart.class" height=700 width=700>
<param name="cols" value="4">
<param name="label1" value="2001">
<param name="label2" value="2002">
<param name="label3" value="2003">
<param name="label4" value="2004">

<param name="values1" value="96">


<param name="values2" value="85">
<param name="values3" value="70">
<param name="values4" value="98">
</applet>
</html>
Output:

Q. Write a program to create an applet for displaying different shapes.


import java.awt.*;
import java.applet.*;

Page 26
public class shapes extends Applet
{
public void paint(Graphics g)
{
g.setFont(new Font("Arial",10, 12));
g.drawString("Types of Shapes",150,10);
g.drawLine(20,20,60,60);
g.drawRect(20,70,50,40);
g.setColor(Color.red);
g.fillOval(100,30,40,90);
g.fillRoundRect(30,140,70,40,10,10);
g.fillArc(100,130,90,50,190,190);
}
}

/*<applet code=shapes height=300 width=300>


</applet>
*/
Output:
Javac shapes.java
Appeltviewer shapes.java

Q. Write a program to set background and foreground color using applet

Page 27
import java.awt.*;
import java.applet.*;
public class backfore extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.yellow);

g.setColor(Color.red);
g.drawString("Demo of background and Foreground color",10,50);
}
}
/*<applet code="backfore.class" width=100 height=100>
</applet>
*/
Output:

Q. Write the applets to draw square inside a circle

import java.awt.*;
import java.applet.*;
public class CirSqr extends Applet
{
public void paint(Graphics g)
{
g.drawOval(70,30,100,100);
g.drawRect(90,50,60,60);
}
}

Page 28
/*<applet code="CirSqr.class" height=200 width=200>
</applet> */
Output:

Q. Write the applets to set background with red color and foreground
with blue color.

/*<applet code="backfore.class" width=400 height=400>


</applet>*/
import java.awt.*;
import java.applet.*;
public class backfore extends Applet
{
public void init()
{
setBackground(Color.red);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString("Welcome to graphics programming", 40, 70);
}
}

FontMetrics class

The FontMetrics class is used to return the specific parameters for a particular
Font object. An object of this class is created using the getFontMetrics() methods
supported by the Component class and other classes, such as the Graphics and
Page 29
Toolkit classes. The FontMetrics access methods provide access to the details of
the implementation of a Font object.
The bytesWidth(), charWidth(), charsWidth(), getWidth(), and stringWidth()
methods are used to determine the width of a text object in pixels. These
methods are essential for determining the horizontal position of text on the
screen.

Method Returns Notes

bytesWidth(bytedatea[] Int Returns the width (in


, int offset, int length) pixels) of the bytes
from offset for length

charsWidth(bytedatea[] Int Returns the width (in


, int offset, int length) pixels) of the characters
from offset for length

charWidth(char c) Int How wide is this one


character?

charWidth(char c) Int How wide is this one


character?

getFont() Font What is the current


font?

getHeight() Int What is the standard


height of this font?

getMaxAdvance() Int What is the largest gap


between characters?

getWidths() Int[] Returns a 256 cell array


of the advance widths
for the first 256
characters in this font

stringWidth(String str) Int This is how wide the


string would be on
screen (in pixels)

notepad

Class GraphicsEnvironment
The GraphicsEnvironment class describes the collection
of GraphicsDevice objects and Font objects available to a Java application on a
particular platform.

Page 30
getAllFonts()
public abstract Font[] getAllFonts()
Returns an array containing a one-point size instance of all fonts available in
this GraphicsEnvironment. Typical usage would be to allow a user to select a
particular font. Then, the application can size the font and set various font
attributes by calling the deriveFont method on the chosen instance.

This method provides for the application the most precise control over
which Font instance is used to render text. If a font in
this GraphicsEnvironment has multiple programmable variations, only one
instance of that Font is returned in the array, and other variations must be
derived by the application.
If a font in this environment has multiple programmable variations, such as
Multiple-Master fonts, only one instance of that font is returned in the Font array.
The other variations must be derived by the application.
Returns:

an array of Font objects


getAvailableFontFamilyNames()
public abstract String[] getAvailableFontFamilyNames()
Returns an array containing the names of all font families in
this GraphicsEnvironment localized for the default locale, as returned
by Locale.getDefault().
Typical usage would be for presentation to a user for selection of a particular
family name. An application can then specify this name when creating a font, in
conjunction with a style, such as bold or italic, giving the font system flexibility in
choosing its own best match among multiple fonts in the same font family.
Returns:
an array of String containing font family names localized for the default
locale, or a suitable alternative name if no name exists for this locale.

Example:
import java.awt.GraphicsEnvironment;

public class getfontfamily


{
public static void main(String[] args)
{
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
System.out.println("\nFonts available on this platform: ");

Page 31
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
return;
}
}

Output:
Fonts available on this platform:
Agency FB
Algerian
Arial
Arial Black
Arial Narrow
Arial Rounded MT Bold
Bahnschrift
Baskerville Old Face
Bauhaus 93
Bell MT
Berlin Sans FB
Berlin Sans FB Demi
Bernard MT Condensed
Blackadder ITC
Bodoni MT
Bodoni MT Black
Bodoni MT Condensed
Bodoni MT Poster Compressed
Book Antiqua
Bookman Old Style
Bookshelf Symbol 7
Bradley Hand ITC
Britannic Bold
Broadway
Brush Script MT
Calibri
Page 32
Calibri Light
Californian FB
Calisto MT
Cambria
Cambria Math
Candara
Candara Light
Castellar
Centaur
Century
Century Gothic
Century Schoolbook
Chiller
Colonna MT
Comic Sans MS
Consolas
Constantia
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Corbel
Corbel Light
Courier New
Curlz MT
Dialog
DialogInput
Ebrima
Edwardian Script ITC
Elephant
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Page 33
Felix Titling
Footlight MT Light
Forte
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
Freestyle Script
French Script MT
Gabriola
Gadugi
Garamond
Georgia
Gigi
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Haettenschweiler
Harlow Solid Italic
Harrington
High Tower Text
HoloLens MDL2 Assets
Impact
Imprint MT Shadow
Informal Roman
Ink Free
Javanese Text
Page 34
Jokerman
Juice ITC
Kristen ITC
Kunstler Script
Leelawadee UI
Leelawadee UI Semilight
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Magneto
Maiandra GD
Malgun Gothic
Malgun Gothic Semilight
Marlett
Matura MT Script Capitals
Microsoft Himalaya
Microsoft JhengHei
Microsoft JhengHei Light
Microsoft JhengHei UI
Microsoft JhengHei UI Light
Microsoft New Tai Lue
Microsoft PhagsPa
Microsoft Sans Serif
Microsoft Tai Le
Microsoft YaHei
Microsoft YaHei Light
Microsoft YaHei UI
Microsoft YaHei UI Light
Microsoft Yi Baiti
Page 35
MingLiU-ExtB
MingLiU_HKSCS-ExtB
Mistral
Modern No. 20
Mongolian Baiti
Monospaced
Monotype Corsiva
MS Gothic
MS Outlook
MS PGothic
MS Reference Sans Serif
MS Reference Specialty
MS UI Gothic
MT Extra
MV Boli
Myanmar Text
Niagara Engraved
Niagara Solid
Nirmala UI
Nirmala UI Semilight
NSimSun
OCR A Extended
Old English Text MT
Onyx
Palace Script MT
Palatino Linotype
Papyrus
Parchment
Perpetua
Perpetua Titling MT
Playbill
PMingLiU-ExtB
Poor Richard
Pristina
Page 36
Rage Italic
Ravie
Rockwell
Rockwell Condensed
Rockwell Extra Bold
SansSerif
Script MT Bold
Segoe MDL2 Assets
Segoe Print
Segoe Script
Segoe UI
Segoe UI Black
Segoe UI Emoji
Segoe UI Historic
Segoe UI Light
Segoe UI Semibold
Segoe UI Semilight
Segoe UI Symbol
Serif
Showcard Gothic
SimSun
SimSun-ExtB
Sitka Banner
Sitka Display
Sitka Heading
Sitka Small
Sitka Subheading
Sitka Text
Snap ITC
Stencil
Sylfaen
Symbol
Tahoma
TeamViewer15
Page 37
Tempus Sans ITC
Times New Roman
Trebuchet MS
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Verdana
Viner Hand ITC
Vivaldi
Vladimir Script
Webdings
Wide Latin
Wingdings
Wingdings 2
Wingdings 3
Yu Gothic
Yu Gothic Light
Yu Gothic Medium
Yu Gothic UI
Yu Gothic UI Light
Yu Gothic UI Semibold
Yu Gothic UI Semilight

Page 38

You might also like