Professional Documents
Culture Documents
1
Applets
Program that runs in
appletviewer (test utility for applets)
Web browser (IE, Communicator, google chrome etc.)
Executes when HTML (Hypertext Markup Language) document containing
applet is opened and downloaded
Applications run in command windows
Applets are Java programs that are embedded in web pages
Applets are run by a “Java-enabled” web browser
Applets are similar to applications
May use “worker” classes
Create objects and call methods in the same way
Applets differ from applications in some ways
No main method (typically have init and paint methods)
Start execution with one of the Applet methods
Contents are drawn in an applet “window”
Inherit from the class Applet
Applet Fundamentals
All applets are subclasses of Applet. Thus, all applets must
import java.applet.
Applets must also import java.awt. Recall that AWT stands
for the Abstract Window Toolkit. Since all applets run in a
window, it is necessary to include support for that window.
Applets are not executed by the console-based Java run-time
interpreter. Rather, they are executed by either a Web browser
or an applet viewer.
Execution of an applet does not begin at main( ). Actually,
few applets even have main( ) methods.
Instead, execution of an applet is started and controlled with
an entirely different mechanism.
.
3
Applet Fundamentals
Output to your applet’s window is not performed by
System.out.println( ). Rather, it is handled with various AWT
methods, such as drawString( ), which outputs a string to a
specified X,Y location.
Input is also handled differently than in an application.
Once an applet has been compiled, it is included in an HTML
file using the APPLET tag.
The applet will be executed by a Java-enabled web browser
when it encounters the APPLET tag within the HTML file.
To view and test an applet more conveniently, simply include a
comment at the head of your Java source code file that
contains the APPLET tag. This way, your code is documented
with the necessary HTML statements needed by your applet,
and you can test the compiled applet by starting the applet
4
viewer with your Java source code file specified as the target.
Applet Fundamentals
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet
called MyApplet in a window that is 200 pixels wide and 60
pixels high. Since the inclusion of an APPLET command
makes testing applets easier.
5
The java.awt package
“awt” stands for “Abstract Window Toolkit”
Drawing letters
Setting colors
Choosing fonts
6
Displaying
Java’s graphics capabilities
graphics in Applets
Drawing 2D shapes
Controlling colors
Controlling fonts
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y):
is used to draw the specified string.
public void drawRect(int x, int y, int width, int height):
draws a rectangle with the specified width and height.
public abstract void fillRect(int x, int y, int width, int height):
is used to fill rectangle with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height):
is used to draw oval with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height):
is used to fill oval with the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2):
is used to draw line between the points(x1, y1) and (x2, y2).
Displaying graphics in Applets
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer):
is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle):
is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle):
is used to fill a circular or elliptical arc.
public abstract void setColor(Color c):
is used to set the graphics current color to the specified color.
public abstract void setFont(Font font):
is used to set the graphics current font to the specified font.
Structure of an Applet
import java.applet.*;
Import java.awt.*;
public class ClassName extends Applet {
9
Pixels
• A pixel is a picture (pix) element
– one pixel is one dot on your screen
– there are typically 72 to 90 pixels per inch
• java.awt measures everything in pixels
10
The Drawing Surface
Java’s coordinate system
(0, 0) (50, 0)
(w-1, h-1)
- --- 0101110101
- --- Java compiler 0111011101
1000100010
- -- --- --
WebPage.html
- - - - ---
- - - ---- Browser
- -- --- --
- ---- -- -
Applet displayed
in web page
12
1 // WelcomeApplet.java
2 // A first applet in Java.
3
4 import allows us to use
// Java core packages
5 import java.awt.Graphics; // import class Graphics
6
predefined classes (allowing
7 us topackages
// Java extension use applets and
8 graphics, in this case).
import javax.swing.JApplet; // import class JApplet
9
10 public class WelcomeApplet extends JApplet {
11 Java applet
13
A Simple Java Applet: Drawing a String
1 // WelcomeApplet.java
2 // A first applet in Java.
– Comments
• Name of source code and description of applet
14
A Simple Java Applet: Drawing a String
15
A Simple Java Applet: Drawing a String
10 public class WelcomeApplet extends JApplet {
17
A Simple Java Applet: Drawing a String
13 public void paint( Graphics g )
– Method paint
• Lines 13-21 are the definition of paint
• Draws graphics on screen
• void indicates paint returns nothing when finishes task
• Parenthesis define parameter list - where methods receive
data to perform tasks
– Normally, data passed by programmer, as in
JOptionPane.showMessageDialog
• paint gets parameters automatically
– Graphics object used by paint
• Mimic paint's first line
18
A Simple Java Applet: Drawing a String
16 super.paint( g );
– Body of paint
• Method drawString (of class Graphics)
• Called using Graphics object g and dot operator (.)
• Method name, then parenthesis with arguments
– First argument: String to draw
– Second: x coordinate (in pixels) location
– Third: y coordinate (in pixels) location
– Java coordinate system
• Measured in pixels (picture elements)
• Upper left is (0,0)
19
Compiling and Executing WelcomeApplet
20
Compiling and Executing WelcomeApplet
1 <html>
2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>
21
Compiling and Executing WelcomeApplet
1 <html>
2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>
22
Compiling and Executing WelcomeApplet
To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it.
javac FirstApplet.java
If no errors, bytecodes stored in FirstApplet.class
After that run it by: appletviewer FirstApplet.java. Now Html file is not
required but it is for testing purpose only.
appletviewer FirstApplet.java
/*
<applet code=“FirstApplet.class" height=“300" width=“300" border="1">
</applet>
*/
//FirstApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
23
Creating and Executing Applets using NetBeans
Click on fileNew Project
From Catagoires select Java and from Projects select
Java Application then press Next
Set project name and uncheck the “Create Main
Class” because applets do not contain main methods
and click “Finish” button.
In your package name, right click on source packages,
selectApplet
Now set the class name of your applet and click on
“Finish Button”
An editor for applets will be opened, write applet
program and save
Run the applet by pressing shift+F6 24
Applet program to calculate factorial of a number
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
public class FactApplet extends Applet
{
long fact;
public void init()
{
String snumber;
int number;
snumber=JOptionPane.showInputDialog("Enter any number");
number=Integer.parseInt(snumber);
fact=1;
for (int i=1;i<=number;i++)
fact*=i;
}
public void paint(Graphics g)
{
g.drawString("the factorial of given number is "+fact,10,100);
}
}
2002 Prentice Hall. All rights reserved.
Applet program to display current date within rectangle
import java.applet.Applet;
import java.awt.*;
import java.util.Date;// used to access Date object
public class Wellcome extends Applet
{
public void paint(Graphics g)
{
Date dt = new Date();
g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
g.setColor(Color.BLUE);
g.drawRect(10,100,400,100);
g.setColor(Color.PINK);
g.drawString("To day is "+ dt,10,150);
}
}
Program Output
– Method init
• Normally initializes instance variables and applet class
• Guaranteed to be first method called in applet
• First line must always appear as above
– Returns nothing (void), takes no arguments
15 {
– Declare variables
– Two types of variables
• Reference variables (called references)
– Refer to objects (contain location in memory)
• Objects defined in a class definition
• Can contain multiple data and methods
– paint receives a reference called g to a Graphics
object
– Reference used to call methods on the Graphics object
• Primitive data types (called variables)
– Contain one piece of data
• Method JOptionPane.showInputDialog
• Prompts user for input with string
• Enter value in text field, click OK
– If not of correct type, error occurs
– In Chapter 14 learn how to deal with this
• Returns string user inputs
• Assignment statement to string
– Lines 26-27: As above, assigns input to secondNumber
– Assignment statement
• sum an instance variable, can use anywhere in class
– Not defined in init but still used
What is an Event?
Change in the state of an object is known as event i.e. event describes the
change in state of source.
Events are generated as result of user interaction with the graphical user
interface components.
For example, clicking on a button, moving the mouse, entering a character
through key-board, selecting an item from list, scrolling the page are the
activities that causes an event to happen.
Any program that uses GUI (graphical user interface) such as Java
application written for windows, is event driven.
Event-handling model
Three parts
Event source
GUI component with which user interacts
Event object
Encapsulates information about event that occurred
Event listener
Receives event object when notified, then responds
Programmer must perform two tasks
Register event listener for event source
Implement event-handling method (event handler)
Co m p o ne nt De sc rip tio n
JLabel An area where uneditable text or icons can be displayed.
JTextField An area in which the user inputs data from the keyboard.
The area can also display information.
JButton An area that triggers an event when clicked.
JCheckBox A GUI component that is either selected or not selected.
JComboBox A drop-down list of items from which the user can make
a selection by clicking an item in the list or possibly by
typing into the box.
JList An area where a list of items is displayed from which the
user can make a selection by clicking once on any
element in the list. Double-clicking an element in the list
generates an action event. Multiple elements can be
selected.
JPanel A container in which components can be placed.
So m e ba sic GUI c o m po ne nts.
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FactApplet" width=400 height=300>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
2002 Prentice Hall. All rights reserved.
Java Layout Manager 54
The Layout manager is used to layout (or arrange) the GUI java
components inside a Container.
There are many layout managers, but the most frequently used are-
Java BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left,
right, and center.
It is the default layout manager for every java JFrame
Java FlowLayout
FlowLayout is the default layout manager for every JPanel.
It simply lays out components in a single row one after the other.
Java GridBagLayout
It is the more sophisticated of all layouts.
It aligns components by placing them within a grid of cells, allowing
components to span more than one cell.