You are on page 1of 178

Learning & Knowledge Education - India

Day - 4

© 2007 IBM Corporation


Learning & Knowledge Education - India

Day 4 Coverage

• Applets
• Exploring AWT
• Swings

2 © 2007 IBM Corporation


Learning & Knowledge Education - India

Applets

© 2007 IBM Corporation


Learning & Knowledge Education - India

Objectives

• Introduction To Applet

• Web Browser Accessing A Web Page

• Advantages & Disadvantages of Applet

• Introduction To AWT

• Identify various stages of an applet life cycle

• Create Applets in Java

• Identify various graphic methods in Java


4 © 2007 IBM Corporation
Learning & Knowledge Education - India

Introduction to Applet

What is an Applet?

According to Sun:-
"An applet is a small program that is
intended not to be run on its own,
but rather to be embedded inside
another application....

• An applet is a Java program that runs on a web page.

• An applet is compiled on one computer and can run on another


computer through a Java enabled Web browser.

• appletviewer is a program that can run an applet.

5 © 2007 IBM Corporation


Learning & Knowledge Education - India

Web Browsers Accessing a Web Page

Request from the


Internet web browser to web
Web Server server

HTML files,
applets,
images

User enters URL for a web site …………..


6 © 2007 IBM Corporation
Learning & Knowledge Education - India

Web Server Sending Response To Web Browser

Internet
Web Server
HTML file Response from the
web server
HTML file

HTML files,
applets,
images

HTML file embedded with applet tag


sent back from server
7 © 2007 IBM Corporation
Learning & Knowledge Education - India

Web Server Sending Response To Web Browser

Internet
Web Server
HTML file Response from the
web server
HTML file

HTML files,
applets,
images

Applet bytecode sent by the server is


interpreted by the browser
8 © 2007 IBM Corporation
Learning & Knowledge Education - India

Introduction to Applet (Continued)

Advantages of an Applet
• It is simple to make it work across platform.
• It runs in a sandbox, so the user does not need to trust the code, so
it can work without security approval.
• It is supported by most web browsers.
• It will cache in most web browsers, so will quick to load when
returning to a web page.
• The applet can work on all installed versions of Java rather than just
the latest plug – in version only.
• It can improve with use: after a first applet is run, the JVM is already
running and starts quickly, benefiting regular users of Java.

9 © 2007 IBM Corporation


Learning & Knowledge Education - India

Introduction to Applet (Continued)

Disadvantages of an Applet
• It requires the default plug-in, which isn’t available by default on all
web browsers.
• It can’t startup until the JVM is running, and this may have
significant startup time the first time it is used.
• It is considered to difficult to build and design a good user interface
with than with HTML-based technologies.

10 © 2007 IBM Corporation


Learning & Knowledge Education - India

Introduction To AWT

• AWT stands for Abstract Windowing Toolkit. It is a package in Java


that provides support for building GUI.

• The name of the package is java.awt.

• The API of the AWT package consists of a collection of classes and


methods that enables you to design and manage the Graphical User
Interface (GUI) applications.

• The AWT package supports applets, which help in creating containers,


such as frames or panels that run in the GUI environment.

11 © 2007 IBM Corporation


Learning & Knowledge Education - India

Life Cycle of an Applet

• init
 To initialize the applet each time it's loaded (or reloaded).

• start
 To start the applet's execution, such as when the applet's loaded or
when the user revisits a page that contains the applet.
• stop
 To stop the applet's execution, such as when the user leaves the
applet's page or quits the browser.
• destroy
 To perform a final cleanup in preparation for unloading.

Not every applet needs to override every one of these methods.

12 © 2007 IBM Corporation


Learning & Knowledge Education - India

Life Cycle of an Applet (Continued)


Initialization an When the applet is opened for the first time.
Applet using init()

Starting an Applet When the applet receive focus or when it is revisited.


using start()

Stopping an Applet When the applet lost focus or when the user leaves the
using stop() page.

Destroying an
Applet using When an applet is destroyed.
destroy()

13 © 2007 IBM Corporation


Learning & Knowledge Education - India

Security Issues in Context to Applet

• Every browser implements security policies to keep applets from


compromising system security.
• Current browsers impose the following restrictions on any applet that is loaded
over the network:
 An applet cannot load libraries or define native methods.
 It cannot ordinarily read or write files on the host that's executing it.
 It cannot make network connections except to the host that it came from.
 It cannot start any program on the host that's executing it.
 It cannot read certain system properties.
 Windows that an applet brings up look different than windows that an
application brings up.

14 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java

Steps To Create An Applet


1. Create a Java program that will be extended from java.applet.Applet
class.

2. Compile the java program.

3. Create a web page that contains an applet.

4. Run the applet.

15 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java (Continued)

Steps To Create An Applet


1. Create a Java program that will be extended from java.applet.Applet
class.

IsIsa an
method
objectof
import java.awt.*;
that
Graphics
holds
import java.applet.Applet; class,
information
use to
public class MyApplet extends Applet about
draw letters
painting
in
{ an applet
public void paint(Graphics g) It remembers
window
{ what color,
g.drawString(“Welcome To IBM”,50,50); font you are
} using.
}

16 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java

Steps To Create An Applet


2. Compile the java program

C:\> javac MyApplet.java

17 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java

Steps To Create An Applet


3. Create a web page that contains an applet

C:\> edit MyPage.htm

18 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java

Steps To Create An Applet


3. Create a web page that contains an applet

<html>
<body>
<applet code=“MyApplet.class” width=200 height=200></applet>
</body>
</html>

19 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creating Applet in Java

Steps To Create An Applet


4. Run the applet.

C:\> appletviewer MyPage.htm

20 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output in Appletviewer window

21 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output in Web Browser window

22 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

23 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag

• CODE and CODEBASE

 The CODE attribute is used to indicate the name of the class file
that holds the current Java applet.
 The CODE attribute is used when both the .class file and the
.html file are located in the same directory.
 The CODEBASE attribute indicates the pathname where the
.class file is stored.
 The CODEBASE attribute is used, if you store a java file in a
directory different from an HTML file.

24 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

25 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag

• HEIGHT
 Use to specify the height of the applet display area.
 The value may be given in pixels or as a percentage of the
parent element's height.

• WIDTH
 Use to specify the width of the applet display area.
 The value may be given in pixels or as a percentage of the
parent element's width.

26 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

27 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag

• HSPACE
 The HSPACE attribute specify the horizontal space between an
applet and the text.
 The HSPACE attribute controls the space to the left and right
side of an applet.

 
• VSPACE
 The VSPACE attribute specify the vertical space between an
applet and the text.
 The VSPACE attribute controls the space above and below an
applet.

28 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

29 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag

• ALIGN
 The ALIGN attribute specifies the alignment of an applet.
 You can specify various values to the ALIGN attribute, such as
LEFT, RIGHT, BOTTOM, TOP, BASELINE, MIDDLE,
TEXTTOP, ABSBOTTOM, and ABSMIDDLE.

30 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

31 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag

• The ALT attribute specifies the alternate text to be displayed if the


browser does not support the applet.

32 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME=“parameter_name” VALUE=“value of the parameter”>
</APPLET>
</BODY>
</HTML>

33 © 2007 IBM Corporation


Learning & Knowledge Education - India

Attributes of Java Applet Tag


• Passing Parameters to Applets

 You pass parameters to an applet by using the <PARAM> tag. The


PARAM tag contains the NAME and VALUE attributes.

 The NAME attribute specifies the name of the parameter passed to an


applet, and the VALUE attribute specifies the value of the variable to be
passed.

 The following syntax sets the value of the color as red:


<APPLET CODE=”MyFirstApplet.class” HEIGHT = 20 WIDTH = 20>
<PARAM NAME= “color” VALUE= “Red”>
</APPLET>

34 © 2007 IBM Corporation


Learning & Knowledge Education - India

Applet Retrieving Data From A HTML File

• Getting Parameters in Applets


 You retrieve the parameters passed to an applet by using the
getParameter() method in the Java file.

 This method accepts a String argument that indicates the


name of the parameter.

 The getParameter() method returns a String value that


specifies the corresponding value of that parameter.

35 © 2007 IBM Corporation


Learning & Knowledge Education - India

Java’s coordinate system


Java uses (x,y) coordinate system
(0,0) is the top left corner (50, 0)

(0,20) is 20 pixels down from (0,0)

(50,0) is 50 pixels to the right of (0,0)

(20,50) is 20 pixels down from (0,0)


and 50 pixels to the right of (0,0)

(w -1, h -1) is just inside the bottom


right corner, where w is the the width
of the window and h is its height

36 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Graphics Class Methods

1. drawLine(x1,y1,x2,y2)

Used to draw lines.

(x1,y1) (x2,y2)

37 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Graphics Class Methods (Continued)

2. drawOval(x,y,width,height)

Used to draw oval or circle shapes.

(starting x
coordinate, starting y height
coordinate)

width

38 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Graphics Class Methods (Continued)

3. fillOval(x,y,width,height)

Used to draw oval or circle shapes with the current color.

(starting x
coordinate, starting y height
coordinate)

width

39 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Graphics Class Methods (Continued)

4. drawRect(x,y,width,height)

Used to draw rectangle or square shapes.

(starting x
oordinate, starting y
coordinate) height

width

40 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Graphics Class Methods (Continued)

5. fillRect(x,y,width,height)

Used to draw filled rectangle or square shapes with the current color.

(starting x
coordinate, starting y
coordinate)
height

width

41 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Setting a Color

• setColor() – is used to set a color for the graphics object.


• The Graphics class object will remember the color setting until
and unless you are changing it.
import java.applet.Applet;
import java.awt.*;
public class MyApplet extends Applet { Color is a class
Sample having some
public void paint(Graphics g) {
program static fields like
using
g.setColor(Color.BLUE); blue, green,
setColor()
g.drawString(“Welcome To IBM”,50,50); red etc.
method
g.setColor(new Color(255,0,0));
g.drawLine(50,52,142,52);
}
}
42 © 2007 IBM Corporation
Learning & Knowledge Education - India

More on java.awt.Graphics class

Setting a Font
• Font class is used to define the properties of a font.
• Font object has a:
 Font Name – Arial, Times New Roman, SansSerif
 Font Style – Normal, Bold, Italic
 Font Size - 12 point = normal size
• setFont() – is used to set a font for the graphics object.
• The Graphics class object will remember the font setting until and unless you are changing it.

43 © 2007 IBM Corporation


Learning & Knowledge Education - India

More on java.awt.Graphics class

Setting a Font Example

Sample
program
using
import java.applet.Applet;
setFont()
import java.awt.*; method
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.setFont(new Font(“Arial”,Font.BOLD,15);
g.drawString(“Welcome To IBM”,50,50);
}
}

44 © 2007 IBM Corporation


Learning & Knowledge Education - India

Exercise
Write a program in Applet to draw the shapes as given below?

45 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary

• An Applet is a Java program that you can embed in a HTML page


and access on a Web browser.
• Java Application Program Interface (API) includes a package
java.applet, which contains the Applet class.
• Applet has limited access to system resources and prohibited access
to other systems on the network.
• All the applets are subclasses of the Applet class.
• The life cycle of an applet consists of the following methods:
 init()
 start()
 stop()
 destroy()
• You can run an applet in an appletviewer or a Web browser.

46 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary (Continued)
• To run an applet in appletviewer, include an HTML tag as a comment.
Compile the applet using javac command and run the applet giving the
following command:
appletviewer className.java
• The parameters of an applet HTML tag are:
 CODE, CODEBASE
 WIDTH, HEIGHT
 HSPACE, VSPACE
 ALT
 <PARAM> tag
• The various drawing methods in Java are:
 drawString()
 drawLine()
 drawRect(
 drawOval()
 fillOval()
47 © 2007 IBM Corporation
Learning & Knowledge Education - India

References

http://java.sun.com/j2se/1.4.2/docs/api/index.html

48 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT and Event Handling

© 2007 IBM Corporation


Learning & Knowledge Education - India

Objectives
• Overview of AWT
• Components and Containers
• Layout Managers
• Frame
• Panel
• Dialog
• Button
• TextField
• Checkbox
• RadioButton

50 © 2007 IBM Corporation


Learning & Knowledge Education - India

Objectives (Contd.)

• Events in AWT
• Types of Events
• Event Dispatching
• Event Handling
• Event Listeners
• Overview of Adapter class

51 © 2007 IBM Corporation


Learning & Knowledge Education - India

Overview of AWT

• AWT stands for Abstract Window ToolKit.


• It is a portable GUI library between different platforms
• The user interfaces provided by are implemented by using each
platform’s native GUI interface

Package for AWT:


java.awt

52 © 2007 IBM Corporation


Learning & Knowledge Education - India

Overview of AWT

• Building applications with graphical user interfaces is easily


broken into two parts

1. Making an Interface

2. Defining Its Behavior

53 © 2007 IBM Corporation


Learning & Knowledge Education - India

Components

• A graphical user interface is built of graphical elements called


components
• Different Type of Components are

Choice
Label
AWT Components
TextBox

Etc…. List
54 © 2007 IBM Corporation
Learning & Knowledge Education - India

Container

• Components are placed within Containers


• Containers maintain the layout of the components

Applet
Panel

AWT Containers Frame

Window
Dialog

55 © 2007 IBM Corporation


Learning & Knowledge Education - India

Container

• Each Container comes with a default Layout Manager

What is
Layout
Manager???

56 © 2007 IBM Corporation


Learning & Knowledge Education - India

Layout Manager

• Layout Management is the process of determining the size and


positions of the components.

BorderLayout

FlowLayout
Types of Layout GridLayout
Managers GridBagLayout

CardLayout

BoxLayout
57 © 2007 IBM Corporation
Learning & Knowledge Education - India

Layout Manager Hierarchy

javax.lang.Object

java.awt.BorderLayout java.awt.FlowLayout java.awt.GridBagLayout

java.awt.GridLayout
java.awt.CardLayout

58 © 2007 IBM Corporation


Learning & Knowledge Education - India

Default Layout Manager of Containers

BorderLayout FlowLayout

Window Panel

What would be
the Layout of
Frame, Dialog
and Applet????

59 © 2007 IBM Corporation


Learning & Knowledge Education - India

BorderLayout

• A BorderLayout has five zones


where the components can be
added.
• Each zone can have only one
single Component.
• The container’s add() method is
used to add the component
• It is the default layout manager
of Frame and Dialog

60 © 2007 IBM Corporation


Learning & Knowledge Education - India

FlowLayout

• FlowLayout arranges components from left to right in a flow


• FlowLayout can use multiple rows if the horizontal space in the
container is too small to hold the components
• It is the default layout manager of Panel and Applet

61 © 2007 IBM Corporation


Learning & Knowledge Education - India

Hierarchy of AWT Container and Component

62 © 2007 IBM Corporation


Learning & Knowledge Education - India

Package details

• All Container Classes except Applet are placed in :


 java.awt package
• All Component Classes are placed in
 java.awt package

The Applet container


is placed in
java.applet

63 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creation of Frame

• In the Java AWT, top-level windows are represented by the


Frame class
• The most common method of creating a frame is by using single
argument constructor of the Frame class that contains the single
string argument which is the title of the window or frame.

Frame frame=new Frame(“New Window”);

64 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of a Frame
import java.awt.*;
public class MyApp
{
Frame frame;
MyApp()
{
frame=new Frame(“My First Application”);
frame.setSize(200,200);
frame.setVisible(true);
}
public static void main(String s[])
{
new MyApp();
}
}

65 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of MyApp

66 © 2007 IBM Corporation


Learning & Knowledge Education - India

Panel

• Panel is the simplest container class. A panel provides space in


which an application can attach any other component, including
other panels.
• The default layout manager for a panel is the FlowLayout layout
manager.

67 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of a Panel

import java.awt.*;
public class MyApp extends Frame
{
Panel p1;
MyApp()
{ super("My Application");
p1=new Panel();
p1.setBackground(Color.GREEN);
setBackground(Color.RED);
add(p1,BorderLayout.NORTH);
setSize(200,200);
setVisible(true);
}

68 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (Contd.)

public static void main(String args[])


{
new MyApp();
}
}

69 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of Example

70 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Components

• Labels:
 Labels provide user prompts, and for displaying information
that should not be modified by users
Label l=new Label(“Name”);
• Button
 This is the component of Java Abstract Window Toolkit and is
used to trigger actions and other events required for your
application.
Button button=new Button(“Click”);

71 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Component

• Checkbox
 This component allows the user to change the state of the component
Checkbox Checkbox=new Checkbox(“OptionalCheckbox1”);
• Radiobutton
 This is the special case of the Checkbox component of Java AWT
package. This is used as a group of checkboxes which group name is
same.
 Only one Checkbox from a Checkbox Group can be selected at a
time.
CheckboxGroup cbg=new CheckboxGroup();
Checkbox radiobutton1=new Checkbox(“One”,cbg,false);
Checkbox radiobutton2=new Checkbox(“Two”,cbg,false);

72 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Component

• TextArea
 This is the text container component of Java AWT package.
 This component can contain multiple lines.
TextArea ta=new TextArea(20,5);
• TextField
 This is also the text container component of Java AWT
package. This component contains single line and limited text
information.
TextField tf=new TextField(20);

73 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of the AWT Components

import java.awt.*;
public class MyApp extends Frame
{
Label feedback,name,hobbies,gender;
Button submit,cancel;
TextArea ta;
TextField tf;
Checkbox cb1,cb2,cb3,rb1,rb2;
CheckboxGroup cbg;
Panel p1,p2,p3,p4,p5;
GridLayout layout;

74 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (contd)

public MyApp()

{ super("My First Application");


layout=new GridLayout(5,1);
setLayout(layout);
p1=new Panel();
p2=new Panel();
p3=new Panel();
p4=new Panel();
p5=new Panel();

75 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (contd)

feedback=new Label("Feedback");
name=new Label("Name");
hobbies=new Label("Hobbies");
gender=new Label("Gender");
submit=new Button("Submit");
cancel=new Button("cancel");
ta=new TextArea(4,20);
tf=new TextField(20);
cb1=new Checkbox("Reading");
cb2=new Checkbox("Philantropy");
cb3=new Checkbox("Painting")

76 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (contd)

cbg=new CheckboxGroup();
rb1=new Checkbox("Male",cbg,false);
rb2=new Checkbox("Female",cbg,false);
p1.add(name);
p1.add(tf);
p2.add(gender);
p2.add(rb1);
p2.add(rb2);
p3.add(hobbies);
p3.add(cb1);
p3.add(cb2);
p3.add(cb3);

77 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (contd)

p4.add(feedback);
p4.add(ta);
p5.add(submit);
p5.add(cancel);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
setSize(400,400);
setVisible(true);
}

78 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example (contd)

public static void main(String args[])


{
new MyApp();
}
}

79 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of the Example

80 © 2007 IBM Corporation


Learning & Knowledge Education - India

Events in AWT

• An event describes, in sufficient detail, a particular user action.


• There are many types of events that are generated by an AWT
Application.
• These events are used to make the application more effective
and efficient.

81 © 2007 IBM Corporation


Learning & Knowledge Education - India

Types of AWT Events

AWTEvent

AdjustmentEvent ActionEvent ComponentEvent

InputEvent FocusEvent ContainerEvent

ItemEvent ComponentEvent PaintEvent

WindowEvent
KeyEvent

TextEvent MouseEvent

82 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Event

• ActionEvent:
 It indicates the component-defined events occurred i.e. the event
generated by the component like Button, Checkboxes etc..

• MouseEvent:
 The MouseEvent class handle all events generated during the
mouse operation for the object. That contains the information
whether mouse is clicked or not if clicked then checks the pressed
key is left or right.

83 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Event

• WindowEvent :
 If the window or the frame of  your application is changed
(Opened, closed, activated, deactivated or any other events
are generated), WindowEvent is generated.
• FocusEvent:
 This class indicates about the focus where the focus has
gained or lost by the object.

84 © 2007 IBM Corporation


Learning & Knowledge Education - India

AWT Event

• TextEvent
 TextEvent is generated when the text of the object is
changed.
• KeyEvent
 The KeyEvent class handles all the indication related to the
key operation in the application if you press any key for any
purposes of the object then the generated event gives the
information about the pressed key.

85 © 2007 IBM Corporation


Learning & Knowledge Education - India

Event Dispatching

Consider the Following

86 © 2007 IBM Corporation


Learning & Knowledge Education - India

Event Handling
Mo
us
Su eC
ge mitb lick
ts
Submit Button to butto
Frame the ha n
does not have a ev ndle
en
t
Event Handler
Panel

Display Reset

Panel Does not


Control is
passed to the have a Handler
Co
pa ntr Panel
th sse ol i
e
F r d to s
am
e
87 © 2007 IBM Corporation
Learning & Knowledge Education - India

Event Dispatch and Propogation

• When the user clicks into “submit” button the java language run-time
system gathers information about the event
• This information is packaged within an instance of the Event Class
• The java-run time then offers the Component to handle the event
• If the event is not handled by the component ,then the next higher
component is given an opportunity

88 © 2007 IBM Corporation


Learning & Knowledge Education - India

Event Listener

• An object that would like to be notified of and respond to an


event is an event listener.
• An object that generates a particular kind of event, called an
event source, maintains a list of listeners that are interested in
being notified when that kind of event occurs.
• When the event source generates an event the event source
notifies all the listener objects that the event has occurred.

89 © 2007 IBM Corporation


Learning & Knowledge Education - India

Event Listeners

• A Listener must be added to a component to react to the events


occurring on the component
• An event is a component’s way of letting the listener know about
that something has happened
• A component must have a way to register and deregister
listeners
• The components must track its Listeners and pass on the events
to those listeners

90 © 2007 IBM Corporation


Learning & Knowledge Education - India

Listener Interface

• An event Listener interface defines the methods used by a method to


dispatch events
• Each event will have one corresponding dispatch method in the listener
interface.
• A listener Interface takes the following format:
 public interface XXXInterface extends EventListener
{
somethingHappened(XXXEvent e);
somethingElseHappend(XXXEvent e);
}

91 © 2007 IBM Corporation


Learning & Knowledge Education - India

Some Common EventListeners

Event Listener Listener methods Registered On

ActionListener actionPerformed() AbstractButton, Button,


ButtonModel, ComboBoxEditor,
JComboBox, JFileChooser,
JTextField, List, MenuItem,
TextField, Timer

ItemListener itemStateChanged() CheckBox,Choice etc

MouseListener mouseClicked(),mousePressed(),m Component


ouseRelaesed(),mouseEntered(),m
ouseExited()

TextListener textValueChanged() TextComponent

MouseMotionListener mouseDragged(),mouseMoved() Component

92 © 2007 IBM Corporation


Learning & Knowledge Education - India

Some Common EventListeners

Event Listener Listener methods Registered On

WindowListener windowActivated(), Window


windowClosed(), windowClosing(),
windowDeactivated(),
windowDeiconified(),
windowIconified(),
windowOpened()

FocusListener focusGained(),focusLost() Component

KeyListener keyTyped(),keyReleased(),keyPres Component


sed()

93 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example

import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame implements ActionListener
{ Button b1,b2;
TextField t1;
Panel p1;
MyApplication()
{ b1=new Button(“Display”);
b2=new Button(“Clear”);
p1=new Panel();
t1=new TextField(20);

94 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example contd.

Bu
wi tton
th s
an reg
Ac ist
b1.addActionListener(this);
tio ere
nL d
ist
b2.addActionListener(this); en
er
p1.add(b1);
p1.add(b2);
add(p1,BorderLayout.NORTH);
add(t1,BorderLayout.SOUTH);
setSize(400,400);
setVisible(true);
}

95 © 2007 IBM Corporation


Learning & Knowledge Education - India

Implementing the Action Listener

public void actionPerformed(ActionEvent e)


{ if(e.getSource()==b1)
{ t1.setText(“Welcome to IBM”);
}
else
{ t1.setText(“ “);
}
}
public static void main(String s[])
{ new MyApp();
}
}

96 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of Example

Click on the Display Button Click On the Reset Button

Welcome to IBM Message is Removed


Message Appears

97 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example

import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame implements MouseListener
{ Button b1;
TextField t1;
Panel p1;
MyApplication()

{
b1=new Button("Display");
t1=new TextField(20);
p1=new Panel();

98 © 2007 IBM Corporation


Learning & Knowledge Education - India

Implementing MouseListener

b1.addMouseListener(this); Re Butto
g
p1.add(b1); Mo ister n is
use ed
add(p1,BorderLayout.NORTH); Lis to a
ten
add(t1,BorderLayout.SOUTH); er
setSize(400,400);
setVisible(true);}
public void mouseEntered(MouseEvent e)
{
b1.setBackground(Color.RED);
}
public void mouseClicked(MouseEvent e)
{ t1.setText("Welcome to IBM");
}

99 © 2007 IBM Corporation


Learning & Knowledge Education - India

Implementing MouseListener

public void mouseExited(MouseEvent e)


{ Though the
b1.setBackground(Color.BLUE); application doe
s not
} need to respon
d to
public void mousePressed(MouseEvent e) these activities
,
{} blank
public void mouseReleased(MouseEvent e) implementation
s
must be provid
{} ed

public static void main(String s[])


{
new MyApplication();
}}

100 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of the Example

Display

Mo
us
ed Button eP
nter oin
t er
E E xi
int er Clicke ted
P o
us
e d
Mo

Welcome to IBM
Message Appears

Back
101 © 2007 IBM Corporation
Learning & Knowledge Education - India

Overview of Adapter Classes

• Adapter classes are used to reduce the code for Event Listeners
• We can avoid implementing all of the unneeded methods by
taking advantage of the adapter classes

All adapter classes are in:


java.awt.event package

102 © 2007 IBM Corporation


Learning & Knowledge Education - India

Adapter classes

• ComponentAdapter
• ContainerAdapter
• WindowAdapter
• MouseAdapter
• MouseMotionAdapter
• WindowAdapter
• FocusAdapter

103 © 2007 IBM Corporation


Learning & Knowledge Education - India

MouseAdapter class

package java.awt.event;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {} }

104 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example using an Adapter class

import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame
{
Button b1;
TextField t1;
Panel p1;
MyApplication()

{
b1=new Button("Display");
t1=new TextField(20);
p1=new Panel();

105 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example(contd)

b1.addMouseListener(new HandleEvent())
p1.add(b1);
add(p1,BorderLayout.NORTH);
add(t1,BorderLayout.SOUTH);
Inner Class
setSize(400,400);
extending the
setVisible(true);}
Mouse Adapter
public class HandleEvent extends MouseAdapter
{
public void mouseEntered(MouseEvent e)
{
b1.setBackground(Color.RED);
}

106 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example(Contd)

public void mouseClicked(MouseEvent e)


{ t1.setText("Welcome to IBM");
}
public void mouseExited(MouseEvent e)``
{
b1.setBackground(Color.BLUE);
}
}
public static void main(String s[])
{
new MyApplication();
}
}
output

107 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary

• AWT stands for Abstract Window ToolKit.


• It is a portable GUI library between different platforms
• All AWT components are found in java.awt package
• The defaut layout of Panel is FlowLayout
• The other layouts also can be set on the containers by using setLayout()
method
• A Panel has to be placed on another container to make it visible
• Some of the common AWT Components are:
Labels,Button,Checkbox,TextArea,TextField
• An event describes in sufficient detail,a particular user action

108 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary (Contd.)

• Some of the different types of AWTEvents are:


ActionEvent,ComponentEvent,ItemEvent,FocusEvent,MouseEvent,Ke
yEvent,etc
• An object that would like to be notified of and respond to an event
is an event listener
• An object that generates a particular kind of event, called an event
source
• A Listener must be added to a component to react to the events
occurring on the component
• A component must have a way to register and deregister listeners

109 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary (Contd.)

• An event Listener interface defines the methods used by a method to


dispatch events
• Common EventListeners are:
WindowListener,MouseListener,MouseMotionListener,FocusLister,Text
Listener,KeyListener
• Adapter classes are used to reduce the code for Event Listeners
• We can avoid implementing all of the unneeded methods by taking
advantage of the adapter classes
• Common Adapter classes are
ComponentAdapter, ContainerAdapter, WindowAdapter,
MouseAdapter,MouseMotionAdapter,WindowAdapter

110 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding

1. Frame is a subclass of .
a. Panel
b. Window
c. Applet
d. Dialog`

2. The default layout of Frame is


a. GridLayout
b.FlowLayout
c. BorderLayout
d. GridBagLayout

111 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

3. Consider the following code:


Frame f=new Frame()
Button b1=new Button(“One”);
f.add(b1);
The buttons b1 will be added in
a. Northern region of the Frame
b. Southern region of thr Frame
c. Central region of the Frame
d. Eastern region of the frame

112 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

4. The setVisible(true) method can make a Panel visible


a. True
b. False

5. An object that would like to be notified of and respond to an event is an ______________


a. Event Listener
b. Event source
c. Adapter Interface
d. Action Class

113 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

6. Consider the following code and select the correct statement


Button b1=new Button(“Click”);
b1.addActionListener();
a. The button component is registered with ActionListener
b. the code will give a compile time error
c. buttons cannot be registered with ActionListener
d. none of the above

114 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

7. MouseListener interface is within the package


a. java.awt.event
b. javax.event
c. java.swing.event
d. java.event
8. An object that generates a particular kind of event, called
a. event handler
b. event adapter
c. event source
d. event dispatcher

115 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

9. Consider the following program and select the correct statement


class Test extends Frame implements ActionListener
{ Button b1;
Test()
{ b1=new Button(“Click”);
b1.addActionListener(this);
add(b1);
setSize(200,200);
setVisible(true);
}
public static void main(String s[])
{
new Test();
}}

116 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

a. Code will result in compile time error because ActionListener is an


adapter class and has to be extended
b. Code will result in compile time error as Test class cannot extend and
implement at the same time
c. Code Compiles without error

d. Code will result in compile time error as the method


actionperformed(ActionEvent e) of the ActionListener interface has not
been given an implementation

117 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (contd.)

10. Adapter class belongs to the package


a. java.awt.event
b.javax.awt.event
c.java.event
d. javax.event

118 © 2007 IBM Corporation


Learning & Knowledge Education - India

User Interfaces with


Java Foundation
Classes (Swings)

© 2007 IBM Corporation


Learning & Knowledge Education - India

Objectives
• Overview of the JFC API
• Features of Swing
• Compiling and running Swing Programs
• Swing Components Hierarchy
• Creating Interfaces in Swing
• Frame
• Panel
• Dialogs
• Label
• Text Field
• Button
• Combo Box
• Table

120 © 2007 IBM Corporation


Learning & Knowledge Education - India

Overview of the JFC API


• JFC is composed of Five main Components:
 AWT
 Java 2D
 Accessibility
 Drag and Drop
 Swing

121 © 2007 IBM Corporation


Learning & Knowledge Education - India

What is Swing?
• The Java Swing provides the multiple platform independent APIs
interfaces for interacting between the users and GUIs
components.

All Java Swing


classes are placed
in javax.swing package 

122 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing overview
• Pluggable Look and Feel

 Increases the reliability and consistency of applications and


applets deployed across platforms.

123 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Overview
An object that controls a
component in such a
• MVC Design
way that it responds to
The visual screen user input.
representation of a
View Controller
Controller
component View

An object that defines the


Model
Model component's state

124 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Overview
• Delegate
 A vital part of Swing's
pluggable L&F mechanism
is a user-interface (UI)
object called a delegate.

125 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Component Hierarchy


• The JComponent class is an abstract class. It is the root of
almost all of Swing's user-interface components.
• JComponents's root class is the Object class, which is defined in
the java.lang.Object file.
• JComponent also inherits from the AWT Container and
Component classes.

126 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Component Hierarchy

java.lang.Object

Java.awt.Component

java.awt.Container

javax.swing.JComponent

127 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Component Hierarchy


JComponent
JComboBox

JList
JTextComponent AbstractButton
JLabel

JToggleButton JMenuItem JTree


JTextField JTextArea

JPane
JButton
JCheckBox JRadioButton JMenuBar

JTable
JRadioButtonMenuItem JMenu
JCheckBoxMenuItem
JScrollBar
Awt Equiv Swing Components JTable
128 © 2007 IBM Corporation
Learning & Knowledge Education - India

Look and Feel (LAF)


• "Look" refers to the appearance of GUI widgets

• “Feel" refers to the way the widgets behave.

• One can change the look and Feel at Runtime

129 © 2007 IBM Corporation


Learning & Knowledge Education - India

Available Look and Feel


• Cross-Platform Look and Feel
• Also known as:

Metal
Java LAF

130 © 2007 IBM Corporation


Learning & Knowledge Education - India

Available Look and Feel Contd.


• SystemLookAndFeel

The System LAF is


determined
at Run Time

131 © 2007 IBM Corporation


Learning & Knowledge Education - India

Setting the Look and Feel programmatically


• To change the LAF use the Following:

Pacakge: Class:
javax.swing UIManager

Method:
setLookAndFeel

132 © 2007 IBM Corporation


Learning & Knowledge Education - India

Windows Look and Feel

133 © 2007 IBM Corporation


Learning & Knowledge Education - India

Motif Look and Feel

134 © 2007 IBM Corporation


Learning & Knowledge Education - India

Setting Native Look and Feel


• Most applications should use native look, not default “Java” look.
• Changing is tedious, so use static method.

public class WindowUtilities {


public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: “+ e);
}
}

135 © 2007 IBM Corporation


Learning & Knowledge Education - India

JFrame
• Content pane
 A JFrame contains a content pane in which to add components.
Changing other properties like the layout manager, background
color, etc., also applies to the content pane.
• Layout manager
 The default layout manager is BorderLayout
• Auto Close Behavior
 The JFrame can be automatically closed on clicking on the Close
Button.
• Look and feel
 The default look and feel is Java (Metal), so you have to explicitly
switch the look and feel if you want the native look.

136 © 2007 IBM Corporation


Learning & Knowledge Education - India

JFrame Hierarchy
java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Window

java.awt.Frame

javax.swing.JFrame

137 © 2007 IBM Corporation


Learning & Knowledge Education - India

Creation and Displaying a JFrame


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

public class JFrameExample {


public static void main(String[] args) {
WindowUtilities.setNativeLookAndFeel();
JFrame f = new JFrame("This is a test");
f.setSize(400, 150);
f.setLayout(new FlowLayout());
f.add(new JButton("Button 1"));
f.add(new JButton("Button 2"));
f.add(new JButton("Button 3"));
f.setVisible(true);
}
}

138 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output Of JFrameExample

139 © 2007 IBM Corporation


Learning & Knowledge Education - India

Swing Equivalents of AWT Components


• JLabel
New features: HTML content images, borders
• JButton
New features: icons, alignment, mnemonics
• JPanel
New feature: borders

 Refer to the Component Hierarchy

140 © 2007 IBM Corporation


Learning & Knowledge Education - India

JLabel
• HTML content
 If text is "<html>...</html>", it gets rendered as HTML
 JLabel fonts are ignored if HTML is used. If you use HTML, all
font control must be performed by HTML.
 You must use <P>, not <BR>, to force a line break.
• Other new features:
 images, borders

141 © 2007 IBM Corporation


Learning & Knowledge Education - India

JLabel Example Code


String labelText =
"<html><FONT COLOR=WHITE>WHITE</FONT> and " +
"<FONT COLOR=GRAY>GRAY</FONT> Text</html>";
JLabel coloredLabel =
new JLabel(labelText, JLabel.CENTER);
...
labelText =
"<html><B>Bold</B> and <I>Italic</I> Text</html>";
JLabel boldLabel =
new JLabel(labelText, JLabel.CENTER);
labelText =
"<html>The Applied Physics Laboratory is..." +
"of the Johns Hopkins University." +
"<P>" + ... "...</html>";

142 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of Label example

143 © 2007 IBM Corporation


Learning & Knowledge Education - India

JButton
• Main new feature: icons
 Create an ImageIcon by passing the ImageIcon constructor a
String representing a GIF or JPG file (animated GIFs are
supported!).
 Pass the ImageIcon to the JButton constructor.
• Other features
 HTML content as with JLabel
 Alignment: location of image with respect to text
 Mnemonics: keyboard accelerators that let you use Alt-
someChar to trigger the button.

144 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of JButton (contd.)

JButton button1 = new JButton("Java");


ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);
JButton button3 = new JButton("Java", cup);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition(SwingConstants.LEFT);

145 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of JButton Example

146 © 2007 IBM Corporation


Learning & Knowledge Education - India

JPanel
• Main new feature: borders
 Create a Border object by calling
BorderFactory.createXxxBorder.
 Supply the Border object to the JPanel by means of setBorder.
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder("Java"));
• Other features:
 Layout manager settings
Can pass the layout manager to the JPanel constructor

147 © 2007 IBM Corporation


Learning & Knowledge Education - India

Standard Borders
• Static methods in BorderFactory
 createEmptyBorder(int top, int left, int bottom, int right)
Creates an EmptyBorder object that simply adds space
(margins) around the component.
 createLineBorder(Color color)
 createLineBorder(Color color, int thickness)
Creates a solid-color border
 createTitledBorder(String title)
 createTitledBorder(Border border, String title)
The border is an etched line unless you explicitly provide a
border style in second constructor.

148 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of JPanel
public class SixChoicePanel extends JPanel {
public SixChoicePanel(String title, String[] buttonLabels) {
super(new GridLayout(3, 2));
setBackground(Color.lightGray);
setBorder(BorderFactory.createTitledBorder(title));
ButtonGroup group = new ButtonGroup();
JRadioButton option;
int halfLength = buttonLabels.length/2;
for(int i=0; i<halfLength; i++) {
option = new JRadioButton(buttonLabels[i]);
group.add(option);
add(option);
option = new JRadioButton(buttonLabels[i+halfLength]);
group.add(option);
add(option);
}
}

149 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of JPanel
• Left window uses createLineBorder
• Right window has three SixChoicePanels

150 © 2007 IBM Corporation


Learning & Knowledge Education - India

Other Simple Swing Components

• JCheckBox
 Note uppercase B
(vs. Checkbox in AWT)

• JRadioButton
 Use a ButtonGroup to
link radio buttons

Hierarchy

151 © 2007 IBM Corporation


Learning & Knowledge Education - India

Other Simple Swing Components

• JTextField
 Just like AWT TextField

• JTextArea
 Same as AWT TextArea
 Place in JScrollPane if
you want scrolling

152 © 2007 IBM Corporation


Learning & Knowledge Education - India

Dialogs in Swing
• There are three basic forms of Dialogs:
 Basic Dialog
JDialog
JDialog

 Option Dialog
JOptionPane
JOptionPane

 Chooser Dialog
JFileChooser,JColorChooser
JFileChooser,JColorChooser

153 © 2007 IBM Corporation


Learning & Knowledge Education - India

Using Dialogs
• Use dialogs only for actions that deviate from the primary task
flow.
• Any dialog pauses the interaction of an application with the user.
• Dialogs should ideally be designed such that they could be
ignored altogether, without disrupting the user's ability to
complete their job.

154 © 2007 IBM Corporation


Learning & Knowledge Education - India

JDialog
• It creates a window possessing a title bar, control menu, and
other familiar elements.
• It implements an instance of JContentPane so other components
can easily be added.

155 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of a JDialog
import javax.swing.*;

class TestDialog

{
JFrame parentFrame; Frame on Which the Dialog will be added
JDialog dialog;
JButton button1,button2;
Components which will be added to the Dialog
JLabel label;
JPanel panel;

156 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of a JDialog contd.


public TestDialog()
{
parentFrame=new JFrame();
dialog=new JDialog(parentFrame,"This is a simple Dialog");
label=new JLabel("Want to continue?");
panel=new JPanel();
button1 =new JButton("Yes");
button2=new JButton("NO");
}

157 © 2007 IBM Corporation


Learning & Knowledge Education - India

Example of a JDialog contd.


public void showDialog()
{
parentFrame.setSize(200,200);
parentFrame.setVisible(true);
dialog.add(label,BorderLayout.NORTH);
panel.add(button1);
panel.add(button2);
dialog.add(panel,BorderLayout.SOUTH);
dialog.setSize(100,100);
dialog.setVisible(true);
}

158 © 2007 IBM Corporation


Learning & Knowledge Education - India

JOptionPane
• Very rich class with many options for different types of dialog boxes.
• Methods for different types of Dialogs
 JOptionPane.showMessageDialog
Icon, message, OK button
 JOptionPane.showConfirmDialog
Icon, message, and buttons:
OK, OK/Cancel, Yes/No, or Yes/No/Cancel
 JOptionPane.showInputDialog (2 versions)
Icon, message, textfield or combo box, buttons
 JOptionPane.showOptionDialog
Icon, message, array of buttons or other components

159 © 2007 IBM Corporation


Learning & Knowledge Education - India

JOptionPane Message Dialogs

160 © 2007 IBM Corporation


Learning & Knowledge Education - India

JOption Confirmation Dialog

161 © 2007 IBM Corporation


Learning & Knowledge Education - India

JColorChooser
• To Open a Color Palate
 Call JColorChooser.showDialog
First argument: parent component
Second argument: title string
Third argument: initially-selected Color
• Return value
 Selected Color if "OK" chosen
 null if "Cancel" chosen

162 © 2007 IBM Corporation


Learning & Knowledge Education - India

JColorChooser Example
• Button that lets you change color of window

public void actionPerformed(ActionEvent e) {


Color bgColor
= JColorChooser.showDialog
(this,"Choose Background Color",
getBackground());
if (bgColor != null)
setBackground(bgColor);
}

163 © 2007 IBM Corporation


Learning & Knowledge Education - India

JColorChooser Output

164 © 2007 IBM Corporation


Learning & Knowledge Education - India

JTable
• Is a user-interface component that presents data in a two-
dimensional table format.
• Displays a grid of data consisting of rows and columns similar to
a spreadsheet.

Hierarchy

165 © 2007 IBM Corporation


Learning & Knowledge Education - India

Features of JTable
• Reassessable and reorderable columns.

• Cells that can be displayed using any components through the


use of the Renderer interface. For example, cells can be
equipped with Checkbox controls, choice controls, and so on.

• Cells that can be edited using an editor interface.

• Support for large data sets.

166 © 2007 IBM Corporation


Learning & Knowledge Education - India

JTable Example
Columns of a Table
String[ ] columnNames = {"First Name", "Last Name", "Sport", "# of
Years", "Vegetarian"};
Data to be displayed on the Table
Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5),
new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new
Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new
Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new
Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new
Integer(10), new Boolean(false)} };
Constructing the Table
JTable table = new JTable(data, columnNames);

167 © 2007 IBM Corporation


Learning & Knowledge Education - India

Output of JTable

168 © 2007 IBM Corporation


Learning & Knowledge Education - India

JTableModel
• Every table object uses a table model object to manage the
actual table data. A table model object must implement the
TableModel interface.
• If the programmer does not provide a table model object, JTable
automatically creates an instance of DefaultTableModel

169 © 2007 IBM Corporation


Learning & Knowledge Education - India

Overview of JTree
• JTree is a powerful Swing component for displaying tree-
structured data
• JTree relies on a separate model object to hold and represent
the data that it displays

Hierarchy

170 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary
• The Java Swing provides the multiple platform independent APIs
interfaces for interacting between the users and GUIs components
• The Java Swing follows the MVC design pattern
• All swing based Components are situated in javax.swing package
• JComponent is the supermost class for all swing based components
• Available Look and Feel :
 SystemLookAndFeel
 CrossPlatForm Look and Feel

171 © 2007 IBM Corporation


Learning & Knowledge Education - India

Summary(Contd.)
• There are various Swing equivalents to AWT components with
addtions of HTML labels, Borders, images…etc
• Various components has been added viz
 JTable
 JTree…etc

172 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding


1 The Java Swing provides the multiple platform independent APIs interfaces for
interacting between the users and GUIs components
a. true
b. false

• 2. All swing component classes are placed in


a. java.awt
b. javax.awt
c. javax.swing
d. java.swing

173 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (Contd.)


3 In MVC pattern the controller contols
a. the visual screen representation of a component
b. the objects state
c. a component in such a way that it responds to the user input
d. the life cycle of an object

4. A vital part of Swing's pluggable L&F mechanism is a user-interface (UI) object


called a______________
a. model
b. object
c. class
d. delegate

174 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (Contd.)


5. The root class of the swing components is
a. JFrame class
b. JPanel class
c. JComponent class
d. JWindow class

6.Cross platform look and feel is also known as:


a. Metal
b.System look and feel
c.Windows look and feel
d. Motif look and feel

175 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (Contd.)


7. .Which component in swing represents data in rows and columns?
a. JTextArea
b. JTable
c. JPanel
c. JtabbedPane

8. Every table object uses a table model object to manage the actual table data
a. true
b. false

176 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (Contd.)


9. Consider the following code and select the correct option
String col[]={"FirstName","LastName","marks"};-----line1
Object [][]data={{"Mary","Adams",new Integer(90)},{"Allen","Jones",new
Integer(57)}};-----line 2
JTable table=new JTable(col,data); -----line 3

a. Compilation error at line 1


b. Compilation error at line 2
c. Compilation error at line 3
d. None of the above

177 © 2007 IBM Corporation


Learning & Knowledge Education - India

Test Your Understanding (Contd.)


10. If the programmer does not provide a table model object, JTable automatically
creates an instance of

a. DefaultTableModel
b. JTable
c. JDefaultTableModel
c. JTableModel

178 © 2007 IBM Corporation

You might also like