You are on page 1of 68

Object Oriented Programming

19CSE (2nd Semester)


Chapter#07: Applets & GUI
Programming

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”

 The java.awt package includes classes for:

 Drawing lines and shapes

 Drawing letters

 Setting colors

 Choosing fonts

 If it’s drawn on the screen, then java.awt is probably involved!

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 {

public void init() {


. . . get things started . . .
} // end of init method
public void paint(Graphics graphicsName) {

statements to perform the applet’s task

} // end of paint method

Other method definitions as necessary


} // end of ClassName class

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)

(0, 20) (50, 20)

(w-1, h-1)

• Java uses an (x, y) coordinate system


• (0, 0) is the top left corner
• (50, 0) is 50 pixels to the right of (0, 0)
• (0, 20) is 20 pixels down from (0, 0)
• (w - 1, h - 1) is just inside the bottom right corner, where w
is the width of the window and h is its height
11
Processing an Applet
Hello.java Hello.class

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

12 // draw text on applet’s background extends allows us to inherit the


13 public void paint( Graphics g ) capabilities of class JApplet.
14 {
15 // call inherited version of method paint
16 super.paint( g );
17 Method paint is guaranteed to
Program Output

18 // draw a String at x-coordinate 25 and y-coordinate 25


19
be called in all applets. Its
g.drawString( "Welcome to Java Programming!", 25, 25 );
first
20 line must be defined as above.
21 } // end method paint
22
23 } // end class WelcomeApplet

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

5 import java.awt.Graphics; // import class Graphics


8 import javax.swing.JApplet; // import class JApplet

– Import predefined classes grouped into packages


• import statements tell compiler where to locate classes used
• When you create applets, import the JApplet class (package
javax.swing)
• import the Graphics class (package java.awt) to draw graphics
– Can draw lines, rectangles ovals, strings of characters
• import specifies directory structure

14
A Simple Java Applet: Drawing a String

– Applets have at least one class definition (like applications)


• Rarely create classes from scratch
– Use pieces of existing class definitions
– Inheritance - create new classes from old ones (ch#06)
10 public class WelcomeApplet extends JApplet {

– Begins class definition for class WelcomeApplet


• Keyword class then class name
– extends followed by class name
• Indicates class to inherit from (JApplet)
– JApplet : superclass (base class)
– WelcomeApplet : subclass (derived class)
• WelcomeApplet now has methods and data of JApplet

15
A Simple Java Applet: Drawing a String
10 public class WelcomeApplet extends JApplet {

– Class JApplet defined for us


• Someone else defined "what it means to be an applet"
– Applets require over 200 methods!
• extends JApplet
– Inherit methods, do not have to define them all
• Do not need to know every detail of class Japplet
– Class WelcomeApplet is a blueprint
• appletviewer or browser creates an object of class
WelcomeApplet
– Keyword public required
– File can only have one public class
– public class name must be file name
A Simple Java Applet: Drawing a String
13 public void paint( Graphics g )

– Our class inherits method paint from JApplet


• By default, paint has empty body
• Override (redefine) paint in our class
– Methods paint, init, and start
• Guaranteed to be called automatically
• Our applet gets "free" version of these by inheriting from
JApplet
– Free versions have empty body (do nothing)
– Every applet does not need all three methods
» Override the ones you need
– Applet container “draws itself” by calling method paint

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

– Calls version of method paint from superclass JApplet


– Should be first statement in every applet’s paint method
19 g.drawString( "Welcome to Java Programming!", 25, 25 );

– 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

• Running the applet


– Compile
• javac WelcomeApplet.java
• If no errors, bytecodes stored in WelcomeApplet.class
– Create an HTML file
• Loads the applet into appletviewer or a browser
• Ends in .htm or .html
– To execute an applet
• Create an HTML file indicating which applet the browser (or
appletviewer) should load and execute

20
Compiling and Executing WelcomeApplet
1 <html>
2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>

– Simple HTML file (WelcomeApplet.html)


• Usually in same directory as .class file
• Remember, .class file created after compilation
– HTML codes (tags)
• Usually come in pairs
• Begin with < and end with >
– Lines 1 and 4 - begin and end the HTML tags
– Line 2 - begins <applet> tag
• Specifies code to use for applet
• Specifies width and height of display area in pixels
– Line 3 - ends <applet> tag

21
Compiling and Executing WelcomeApplet
1 <html>
2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>

– appletviewer only understands <applet>


tags
• Ignores everything else
• Minimal browser
– Executing the applet
• appletviewer WelcomeApplet.html
• Perform in directory containing .class file

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 fileNew 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,
selectApplet
 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);
}
}

 2002 Prentice Hall. All rights reserved.


27
1 // Fig. 3.12: AdditionApplet.java Outline
2 2 // Adding
// Adding two
two floating-point
floating-point numbers
numbers.
3 3 import java.awt.Graphics; // import class Graphics
4 // Java core packages AdditionApplet.java
5 import java.awt.Graphics; // import class Graphics
6 5
7 6 public
// Javaclass AdditionApplet
extension packages extends JApplet { 1. import
8 7 import javax.swing.*;
double sum; // sum of the//values
importentered
packagebyjavax.swing
the user
9 8
10 9 public class
2. Class
public voidAdditionApplet
init() extends JApplet {
11 double sum; // sum of values entered by user AdditionApplet
10 {
12
1311 // String firstNumber,
initialize // first string
applet by obtaining
* allows
values entered
from user
any class in the the(extends
by user package JApplet)
1412 public voidsecondNumber;
init() to be used.
// second string entered by user
1513 { double number1, // first number to add 3. Instance variable
1614 String number2;
firstNumber; // second
// first string
number entered
to add by user
1715 String secondNumber; // second string entered by user
18 double number1; // first number to add
4. init
16 // read in first number from user
19 double number2; // second number to addInstance variable sum may be used anywhere
2017 firstNumber =
4.1 methods.
Declare variables
2118 // JOptionPane.showInputDialog(
obtain first number from user
in the class, even in other
2219 firstNumber
"Enter =first
JOptionPane.showInputDialog(
floating-point value" ); Data type double can store floating point
2320 "Enter first floating-point value" ); 4.2
2421 numbers. showInputDialog
// read in second number from user
25 // obtain second number from user
22 secondNumber =
26 secondNumber = JOptionPane.showInputDialog(
2723 JOptionPane.showInputDialog(
"Enter second floating-point value" ); 4.3 parseDouble
2824 "Enter second floating-point value" );
2925 // convert numbers from type String to type double
3026 number1 = Double.parseDouble( firstNumber );
3127 number2
// = Double.parseDouble(
convert secondNumber
numbers from type String to type );
double
32

 2002 Prentice Hall.


All rights reserved.
28
3331 //
// add
add the numbers
numbers Outline
3432 sum = number1 ++ number2;
sum = number1 number2;
35 }
33 }
36
3734 // draw results in a rectangle on applet’s background 5. Draw applet
3835 public void
public void paint(
paint( Graphics
Graphics gg )) contents
39 {
36 {
40 // call inherited version of method paint
4137 // draw the results
super.paint( g ); with g.drawString 5.1 Draw a rectangle
4238 g.drawRect( 15, 10, 270, 20 );
4339 // draw rectangle
g.drawString( "The starting
sum is " from (15,
+ sum, 25,10)
25 that
); is 270 5.2 Draw the results
44 // pixels wide and 20 pixels tall
4540 } g.drawRect( 15, 10, 270, 20 );
4641 }
47 // draw results as a String at (25, 25)
48 1 <html> g.drawString( "The sum is " + sum, 25, 25 );
49 2 <applet code="AdditionApplet.class" width=300 height=50>
50 } // end method paint
3 </applet> drawRect takes the upper left coordinate, width,
51
52 4 </html>
} // end class AdditionApplet and height of the rectangle to draw.

1 <html> HTML file


2 <applet code = "WelcomeLines.class" width = "300" height = "40">
3 </applet>
4 </html>

 2002 Prentice Hall.


All rights reserved.
29
Outline

Program Output

 2002 Prentice Hall.


All rights reserved.
30
Another Java Applet: Adding Floating-Point
Numbers
– Lines 1-2: Comments
5 import java.awt.Graphics;

– Line 5: imports class Graphics


• import not needed if use full package and class name
public void paint ( java.awt.Graphics g )
8 import javax.swing.*;

– Line 8: specify entire javax.swing package


• * indicates all classes in javax.swing are available
– Includes JApplet and JOptionPane
– Use JOptionPane instead of
javax.swing.JOptionPane
• * does not not load all classes
– Compiler only loads classes it uses

 2002 Prentice Hall. All rights reserved.


31
Another Java Applet: Adding Floating-Point
Numbers
10 public class AdditionApplet extends JApplet {

– Begin class definition


• Inherit from JApplet, imported from package
javax.swing
11 double sum; // sum of values entered by user

– Instance variable declaration


• Each object of class gets own copy of the instance variable
• Declared in body of class, but not inside methods
– Variables declared in methods are local variables
– Can only be used in body of method
• Instance variables can be used anywhere in class
• Have default value (0.0 in this case)

 2002 Prentice Hall. All rights reserved.


32
Another Java Applet: Adding Floating-Point
Numbers
11 double sum; // sum of values entered by user

– Primitive data type double


• Used to store floating point (decimal) numbers

14 public void init()

– 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 {

– Begins body of method init


 2002 Prentice Hall. All rights reserved.
33
Another Java Applet: Adding Floating-Point
Numbers
16 String firstNumber; // first string entered by user
17 String secondNumber; // second string entered by user
18 double number1; // first number to add
19 double number2; // second number to add

– 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

 2002 Prentice Hall. All rights reserved.


34
Another Java Applet: Adding Floating-Point
Numbers
16 String firstNumber; // first string entered by user
17 String secondNumber; // second string entered by user
18 double number1; // first number to add
19 double number2; // second number to add

– Distinguishing references and variables


• If data type is a class name, then reference
– String is a class
– firstNumber, secondNumber
• If data type a primitive type, then variable
– double is a primitive data type
– number1, number2

 2002 Prentice Hall. All rights reserved.


35
Another Java Applet: Adding Floating-Point
Numbers
22 firstNumber = JOptionPane.showInputDialog(
23 "Enter first floating-point value" );

• 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

 2002 Prentice Hall. All rights reserved.


36
Another Java Applet: Adding Floating-Point
Numbers
30 number1 = Double.parseDouble( firstNumber );
31 number2 = Double.parseDouble( secondNumber );

– static method Double.parseDouble


• Converts String argument to a double
• Returns the double value
• Remember static method syntax
– ClassName.methodName( arguments )

34 sum = number1 + number2;

– Assignment statement
• sum an instance variable, can use anywhere in class
– Not defined in init but still used

 2002 Prentice Hall. All rights reserved.


37
Another Java Applet: Adding Floating-Point
Numbers
33 }

– Ends method init


• appletviewer (or browser) calls inherited method start
• start usually used with multithreading
– Advanced concept, in Chapter 15
– We do not define it, so empty definition in JApplet used
• Next, method paint called
45 g.drawRect( 15, 10, 270, 20 );

– Method drawRect( x1, y1, width, height )


• Draw rectangle, upper left corner (x1, y1), specified width
and height
• Line 45 draws rectangle starting at (15, 10) with a width of
270 pixels and a height of 20 pixels

 2002 Prentice Hall. All rights reserved.


38
Another Java Applet: Adding Floating-Point
Numbers
48 g.drawString( "The sum is " + sum, 25, 25 );

– Sends drawString message (calls method) to Graphics


object using reference g
• "The sum is" + sum - string concatenation
– sum converted to a string
• sum can be used, even though not defined in paint
– Instance variable, can be used anywhere in class
– Non-local variable

 2002 Prentice Hall. All rights reserved.


39

Life cycle of an Applet


 The basic structure of an applet overrides four Applet methods,
init(), start(), stop(), and destroy(), and the paint() method defined
by the AWT Component class.
 Following are the stages in Applet
1) Applet is initialized.
2) Applet is started
3) Applet is painted.
4) Applet is stopped.
5) Applet is destroyed.
 When an applet begins, the AWT calls the following methods, in
this sequence:
1. init( )
2. start( )
3. paint( )
 When an applet is terminated, the following sequence of method
calls takes place:
1. stop( )
2. 2002
destroy(
Prentice Hall.)All rights reserved.
40

Methods are called in this order

• init and destroy are only called


init() once each
• start and stop are called
start() whenever the browser enters and
leaves the page
do some work • do some work is code called by
your listeners
stop() • paint is called when the applet
needs to be repainted
destroy()
 2002 Prentice Hall. All rights reserved.
// An Applet skeleton.
An Applet Skeleton 41
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}

 2002 Prentice Hall. All rights reserved.


Drawing 2D shapes
 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).
 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.

 2002 Prentice Hall. All rights reserved.


43
Drawing 2D shapes

 2002 Prentice Hall. All rights reserved.


Applet program to draw various 2D shapes
import java.applet.*;
import java.awt.*;
public class GApplet extends Applet
{
public void paint(Graphics g)
{
//setBackground(Color.BLACK); // set background color
g.setColor(Color.RED);
g.drawLine(20, 20, 500, 20);
g.drawRect(20, 40, 200, 40);
g.fillRect(300, 40, 200, 40);
g.drawRoundRect(20, 100, 200, 40, 10, 10);
g.fillRoundRect(300, 100, 200, 40, 10, 10);
g.setColor(Color.GREEN);
g.drawOval(20, 160, 200, 100);
g.fillOval(300, 160, 200, 100);
g.setColor(Color.BLUE);
g.setFont(new Font("Monospaced", Font.PLAIN+Font.BOLD, 18));
g.drawString("Testing custom drawing ...", 150, 300);
}
}
 2002
} Prentice Hall. All rights reserved.
Applet program to draw simple house
//Java Applet program for creating house
import java.awt.*;
import java.applet.*; 
public class HouseApplet extends Applet
{
public void paint(Graphics g)
{
int [] x = {150, 300, 225};
int [] y = {150, 150, 25};
g.drawRect(150, 150, 150, 200); //House
g.drawRect(200, 200, 50, 150); // Door
g.drawOval(200, 75, 50, 50); // Skylight
g.drawPolygon(x, y, 3); // Roof
}
}

 2002 Prentice Hall. All rights reserved.


Applet program to draw simple house
import java.awt.*;
import java.applet.*;
public class Flag extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(50,20,5,300);
g.setColor(Color.green);
g.drawRect(50,18,3,300);
g.setColor(Color.blue);
g.fillRect(55,20,120,30);
g.setColor(Color.black);
g.drawRect(55,20,118,28);
g.setColor(Color.blue);
g.fillRect(55,80,119,30);
g.setColor(Color.black);
g.drawRect(55,80,117,28);
g.setColor(Color.black);
g.drawOval(100,50,30,30);
}
}

 2002 Prentice Hall. All rights reserved.


Java GUI Event Handling 47

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.

How events are handled?


 A source generates an Event and send it to one or more listeners registered
with the source.
 Once event is received by the listener, they process the event and then
return.
 Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.
 2002 Prentice Hall. All rights reserved.
Java GUI Event Handling 48

What is an Event Handling?


 Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
 This mechanism have the code which is known as event handler that is
executed when an event occurs.
 Java Uses the Delegation Event Model to handle the events.
 This model defines the standard mechanism to generate and handle the
events.
 Components of Event Handling
 Event handling has three main components,
 Events : An event is a change in state of an object.
 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.
 Steps to handle events:
 Implement appropriate interface in the class.
 Register the component with the listener.
 2002 Prentice Hall. All rights reserved.
Event-Handling Model

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

 2002 Prentice Hall. All rights reserved.


Java GUI Event Handling 50

Event Classes Description Listener Interface


ActionEvent generated when button is pressed, menu-item is selected, ActionListener
list-item is double clicked
MouseEvent generated when mouse is dragged, moved, clicked, pressed MouseListener
or released and also when it enters or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener


MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
WindowEvent generated when window is activated, deactivated, WindowListener
deiconified, iconified, opened or closed
ComponentEvent generated when component is hidden, moved, resized or set ComponentEventListene
visible r
ContainerEvent generated when component is added or removed from ContainerListener
container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
FocusEvent generated when component gains or loses keyboard focus FocusListener

 2002 Prentice Hall. All rights reserved.


Some basic GUI components.

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.

 2002 Prentice Hall. All rights reserved.


Applet to Calculate factorial of a number 52

import java.awt.event.*;
import java.applet.*;
/*
<applet code="FactApplet" width=400 height=300>
</applet>
*/

public class FactApplet extends Applet implements ActionListener


{
TextField number,factorial; public void actionPerformed(ActionEvent e)
Button compute; {
public void init() String snumber;
{ snumber = number.getText();
Label numberp = new Label("Input Number: "); int inumber = Integer.parseInt(snumber);
Label factorialp = new Label("Factorial: "); factorial.setText(((Double)getFactorial(inumber)).toStr
number= new TextField(30); }
factorial = new TextField(30);
compute = new Button("Compute"); double getFactorial(int k)
add(numberp); {
add(number); double fact = 1;
add(factorialp); for(int i=1;i<=k;i++)
add(factorial); fact = fact * i;
add(compute); return fact;
compute.addActionListener(this); }
} }// end of class body

 2002 Prentice Hall. All rights reserved.


Java GUI Event Handling 53

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.

 2002 Prentice Hall. All rights reserved.


Java Layout Manager 55

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.

What is a container class?


 Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.
 Panel: It is a pure container and is not a window in itself. The sole purpose
of a Panel is to organize the components on to a window.
 Frame: It is a fully functioning window with its title and icons.
 Dialog: It can be thought of like a pop-up window that pops out when a
message has to be displayed. It is not a fully functioning window like the
Frame.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 56

Step-01: Creating a Project


The first step is to create an IDE project for the application that we are going
to develop. Suppose we are creating GUI to perform addition between
numbers, so we will name our project NumberAddition.
 Choose File > New Project. Alternatively, you can click the New Project
icon in the IDE toolbar.
 In the Categories pane, select the Java node. In the Projects pane, choose
Java Application. Click Next.
 Type NumberAddition in the Project Name field and specify a path, for
example, in your home directory, as the project location.
 (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox
and specify the location for the libraries folder. See Sharing a Library with
Other Users in Developing Applications with NetBeans IDE for more
information.
 Deselect the Create Main Class checkbox if it is selected.
 Click Finish.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 57

Step-02: Building the Front End


 To proceed with building our interface, we need to create a Java container
within which we will place the other required GUI components.
 In this step we'll create a container using the JFrame component.
 We will place the container in a new package, which will appear within the
Source Packages node.
Create a JFrame container
1) In the Projects window, right-click the NumberAddition node and
choose New > Other.
2) In the New File dialog box, choose the Swing GUI Forms category and
the JFrame Form file type. Click Next.
3) Enter NumberAdditionUI as the class name.
4) Enter my.numberaddition as the package.
5) Click Finish.
 The IDE creates the NumberAdditionUI form and
the NumberAdditionUI class within the NumberAddition application, and
opens the NumberAdditionUI form in the GUI Builder.
 The my.NumberAddition package replaces the default package.
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 58

Adding Components: Making the Front End


 To proceed Adding Components: Making the Front End
 Next we will use the Palette to populate our application's front end with a
JPanel.
 Then we will add three JLabels, three JTextFields, and three JButtons.
 If you have not used the GUI Builder before, you might find information in
the Designing a Swing GUI in NetBeans IDE tutorial on positioning
components useful.
 Once you are done dragging and positioning the aforementioned components,
the JFrame should look something like the following screenshot.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 59

Adding Components: Making the Front End


 If you do not see the Palette window in the upper right corner of the IDE,
choose Window > Palette.
1) Start by selecting a Panel from the Swing Containers category on Palette and
drop it onto the JFrame.
2) While the JPanel is highlighted, go to the Properties window and click the
ellipsis (...) button next to Border to choose a border style.
3) In the Border dialog, select TitledBorder from the list, and type in Number
Addition in the Title field. Click OK to save the changes and exit the dialog.
4) You should now see an empty titled JFrame that says Number Addition like
in the screenshot. Look at the screenshot and add three JLabels, three
JTextFields and three JButtons as you see above.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 60

Renaming the Components


 In this step we are going to rename the display text of the components that
were just added to the JFrame.
1) Double-click jLabel1 and change the text property to First Number:.
2) Double-click jLabel2 and change the text to Second Number:.
3) Double-click jLabel3 and change the text to Result:.
4) Delete the sample text from jTextField1. You can make the display text
editable by right-clicking the text field and choosing Edit Text from the
popup menu. You may have to resize the jTextField1 to its original size.
Repeat this step for jTextField2 and jTextField3.
5) Rename the display text of jButton1 to Clear. (You can edit a button's text by
right-clicking the button and choosing Edit Text. Or you can click the button,
pause, and then click again.)
6) Rename the display text of jButton2 to Add.
7) Rename the display text of jButton3 to Exit.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 61

Step-03: Renaming the Components


 Your Finished GUI should now look like the following screenshot:

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 62

Step-03: Adding Functionality


 In this step we are going to give functionality to the Add, Clear, and Exit
buttons.
 The jTextField1 and jTextField2 boxes will be used for user input
and jTextField3 for program output - what we are creating is a very simple
calculator. Let's begin.
Making the Exit Button Work
 In order to give function to the buttons, we have to assign an event handler to
each to respond to events.
 In our case we want to know when the button is pressed, either by mouse
click or via keyboard. So we will use ActionListener responding to
ActionEvent.
1) Right click the Exit button. From the pop-up menu choose Events > Action >
actionPerformed. Note that the menu contains many more events you can
respond to! When you select the actionPerformed event, the IDE will
automatically add an ActionListener to the Exit button and generate a
handler method for handling the listener's actionPerformed method.

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 63

Step-03: Adding Functionality.


Making the Exit Button Work
2) The IDE will open up the Source Code window and scroll to where you
implement the action you want the button to do when the button is pressed
(either by mouse click or via keyboard). Your Source Code window should
contain the following lines:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
//TODO add your handling code here:
}
3) We are now going to add code for what we want the Exit Button to do.
Replace the TODO line with System.exit(0);. Your finished Exit button code
should look like this:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 64

Step-03: Adding Functionality.


Making the Clear Button Work
1) Click the Design tab at the top of your work area to go back to the Form
Design.
2) Right click the Clear button (jButton1). From the pop-up menu select Events
> Action > actionPerformed.
3) We are going to have the Clear button erase all text from the jTextFields. To
do this, you will add some code like above. Your finished source code should
look like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
 The above code changes the text in all three of our JTextFields to nothing, in
essence it is overwriting the existing Text with a blank.
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 65

Step-03: Adding Functionality.


Making the ADD Button Work
 The Add button will perform three actions.
1) It is going to accept user input from jTextField1 and jTextField2 and convert
the input from a type String to a float.
2) It will then perform addition of the two numbers.
3) And finally, it will convert the sum to a type String and place it in
jTextField3.
 Lets get started!
1) Click the Design tab at the top of your work area to go back to the Form
Design.
2) Right-click the Add button (jButton2). From the pop-up menu, select Events
> Action > actionPerformed.
3) We are going to add some code to have our Add button work. The finished
source code shall look like this:

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 66

Step-03: Adding Functionality.


Making the ADD Button Work
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to change the value of result from a
//float to a string.
jTextField3.setText(String.valueOf(result));
}

 2002 Prentice Hall. All rights reserved.


Java GUI Building using NetBeans 67

Step-04: Running the Program


To run the program in the IDE:
 Choose Run > Run Project (Number Addition) (alternatively, press F6).
 Note: If you get a window informing you that Project NumberAddition does
not have a main class set, then you should
select my.NumberAddition.NumberAdditionUI as the main class in the same
window and click the OK button.
To run the program outside of the IDE:
1) Choose Run > Clean and Build Main Project (Shift-F11) to build the
application JAR file.
2) Using your system's file explorer or file manager, navigate to
the NumberAddition/dist directory.Note: The location of
the NumberAddition project directory depends on the path you specified
while creating the project in step 3 of the Step 1: Creating a Project
 section.
3) Double-click the NumberAddition.jar file.
 After a few seconds, the application should start.
 Note: If double-clicking the JAR file does not launch the application, see 
this article for information on setting JAR file associations in your operating
 2002 Prentice Hall. All rights reserved.
Java GUI Building using NetBeans 68

Step-04: Running the Program


 You can also launch the application from the command line.
To launch the application from the command line:
1) On your system, open up a command prompt or terminal window.
2) In the command prompt, change directories to
the NumberAddition/dist directory.
3) At the command line, type the following statement:
java -jar NumberAddition.jar
 Note: Make sure my.NumberAddition.NumberAdditionUI is set as the main
class before running the application.
 You can check this by right-clicking the NumberAddition project node in the
Projects pane, choosing Properties in the popup menu, and selecting the Run
category in the Project Properties dialog box.
 The Main Class field should display my.numberaddition.NumberAdditionUI.

 2002 Prentice Hall. All rights reserved.

You might also like