SlideShare a Scribd company logo
1 of 42
Introduction to Applets, Swing &
MVC Architecture
Advanced Java Lab
Introduction to Swing
(Java’s GUI Components)
Introduction to Swing
GUI programming involves a computational model known as event-driven
programming, which means that GUI programs react to events that are generated
mostly by the user’s interactions with elements in the GUI.
Java’s GUI Components
The Java library comes with two separate but interrelated packages of GUI
components, the older java.awt package and the newer javax.swing package.
For the most part, the Swing classes supersede the AWT classes. For example, the
java.awt.Button class is superseded by the javax.swing.JButton class, and the
java.awt.TextField class is superseded by the javax.swing.JTextField class.
Swing V/S AWT
The Swing classes are generally considered to be superior to their AWT
counterparts.
For one thing, Swing components use a sophisticated object-oriented design
known as the model-view-controller (MVC) architecture, which gives them much
greater functionality than their AWT counterparts. For example, whereas an AWT
Button can only have a string as its label, a Swing JButton can use an image as a
label.
Second, Swing components are written entirely in Java which makes them more
portable and enables them to behave the same way regardless of the operating
system on which they are run.
AWT components are called heavyweight because they depend on the native
(peer) system for their drawing and rendering. Because of their portability, Swing
components are considered lightweight.
The Swing GUI components are part of the Java Foundation Classes (JFC), a
collection of classes that do not depend as much on the underlying platform.
Swing V/S AWT
The above figure shows that the top-level Swing classes—the JApplet, JDialog,
JFrame, and JWindow—are direct subclasses of their corresponding AWT
counterparts. The remaining Swing components (Fig. 2, below) are subclasses of
java.awt.Component and java.awt.Container.
Swing V/S AWT
Swing V/S AWT
• It is important to note that the Swing based GUIs are still dependent on
the AWT. Java programs need to have some way to map their windows to
the windowing system used on the native (Windows, Unix, or Macintosh)
platform.
• The AWT’s top-level windows—Window, Frame, Dialog, and Panel—
provide that mapping.
• Also, the JComponent class, which is the basis for all Swing components,
is derived from java.awt.Container.
• Finally, all GUI applications and applets use layout managers (java.-
awt.FlowLayout), fonts (java.awt.Font), colors ( java.awt.Color), and other
non-component classes that are defined in the AWT.
• There is just no way to design a GUI without using AWT classes
The Swing Component Set
Java’s Swing components are defined in a collection of packages named
javax.swing.*.
Swing packages include the following:
javax.swing.event.∗
javax.swing.text.∗
javax.swing.plaf.∗
The javax.swing.event package defines the various Swing events and their
listeners, such as the MenuEvent and the MenuListener. (In the AWT, the AWT
events and listeners were defined in java.awt.event.)
The javax.swing.text package contains the classes for JTextField and
JTextComponent.
The javax.swing.plaf package contains Swing’s look-and-feel classes. The term
plaf is an acronym for pluggable look and feel.
Swing’s platform-independent look and feel is achieved by placing all the
code responsible for drawing a component in a class that is separate from the
component itself. For example, in addition to JButton, the class that defines
the button control, there will be a separate class responsible for drawing the
button on the screen. The drawing class will control the button’s color, shape,
and other characteristics of its appearance.
Model-View-Controller Architecture
Java’s Swing components have been implemented using an
object oriented design known as the model-view-controller
(MVC) model. Any Swing component can be considered in terms
of three independent aspects: what state it’s in (its model), how
it looks (its view), and what it does (its controller).
Model
The model encompasses the state data for each component. For
example, the model of a scrollbar component might contain
information about the current position of its adjustable “thumb,”
its minimum and maximum values, and the thumb’s width
(relative to the range of values). A menu, on the other hand, may
simply contain a list of the menu items the user can select from.
Model-View-Controller Architecture
View
The view refers to how we see the component on the screen. For
example consider an application window on two different GUI
platforms. Almost all window frames will have a titlebar
spanning the top of the window. However, the titlebar may have
a close box on the left side (like the older MacOS platform), or it
may have the close box on the right side (as in the Windows
platform). These are examples of different types of views for the
same window object.
Controller
The controller is the portion of the user interface that dictates
how the component interacts with events. Events come in many
forms - a mouse click, gaining or losing focus, a keyboard event
that triggers a specific menu command, or even a directive to
repaint part of the screen. The controller decides how each
component will react to the event-if it reacts at all.
Model-View-Controller Architecture
Example-1
For example, a button’s role is to appear on the interface waiting to be
clicked. When it is clicked, the button’s appearance changes. It looks
pushed in or it changes color briefly, and then it changes back to its
original (unclicked) appearance. In the MVC model, this aspect of the
button is its view.
Whether a button is enabled or disabled and whether it is pressed or
not are properties of its internal state. Such properties constitute the
button’s model. So we can say that, a button’s view—how it looks—
depends on its model.
Because a button’s state will change when it is clicked or when it is
enabled by the program, some object needs to keep track of these
changes. That part of the component is its controller. Figure-3 shows
how the button’s model, view, and controller interact with each other.
Model-View-Controller Architecture
Figure-3 shows how the button’s model, view, and controller
interact with each other.
The model-view-controller architecture
Model-View-Controller Architecture
Suppose the user clicks the button. This action is detected by the
controller. Whenever the mouse button is pressed, the controller
tells the model to change into the pressed state. The model, in
turn, generates an event that is passed to the view. The event
tells the view that the button needs to be redrawn to reflect its
change in state. When the mouse button is released, a similar
sequence of events occurs. The model is told to change to the
unpressed state. It in turn generates an event, handled by the
view, which changes the button’s appearance.
Model-View-Controller Architecture
Example-2
The following figure-4 shows, how the model, view, and
controller work together to create a scrollbar component
Model-View-Controller Architecture
Example-2
The scrollbar uses the information in the model to determine how far
into the scrollbar to render the thumb and how wide the thumb
should be.
Note that the model specifies this information relative to the
minimum and the maximum. It does not give the position or width of
the thumb in screen pixels—the view calculates that.
The view determines exactly where and how to draw the scrollbar,
given the proportions offered by the model.
The view knows whether it is a horizontal or vertical scrollbar, and it
knows exactly how to shadow the end buttons and the thumb.
Finally, the controller is responsible for handling mouse events on the
component. The controller knows, for example, that dragging the
thumb is a legitimate action for a scroll bar, and pushing on the end
buttons is acceptable as well.
Model-View-Controller Architecture
Example-2
The scrollbar uses the information in the model to determine how far
into the scrollbar to render the thumb and how wide the thumb
should be.
Note that the model specifies this information relative to the
minimum and the maximum. It does not give the position or width of
the thumb in screen pixels—the view calculates that.
The view determines exactly where and how to draw the scrollbar,
given the proportions offered by the model.
The view knows whether it is a horizontal or vertical scrollbar, and it
knows exactly how to shadow the end buttons and the thumb.
Finally, the controller is responsible for handling mouse events on the
component. The controller knows, for example, that dragging the
thumb is a legitimate action for a scroll bar, and pushing on the end
buttons is acceptable as well.
Applets
Applets are small applications that are accessed on an Internet
server, transported over the Internet, automatically installed, and
run as part of a web document. After an applet arrives on the client,
it has limited access to resources so that it can produce a graphical
user interface and run complex computations without introducing
the risk of viruses or breaching data integrity.
A simple applet
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
Applets
• Applets interact with the user through the AWT, not through the
console-based I/O classes. The second import statement imports
the applet package, which contains the class Applet. Every
applet that we create must be a subclass of Applet.
• The SimpleApplet class is public because it will be accessed by
code that is outside the program.
• Inside SimpleApplet, paint( ) is declared. This method is defined
by the AWT and must be overridden by the applet.
• paint( ) is called each time that the applet must redisplay its
output.
• This situation can occur for several reasons. For example, the
window in which the applet is running can be overwritten by
another window and then uncovered. Or, the applet window can
be minimized and then restored.
• paint( ) is also called when the applet begins execution.
Applets
• The paint( ) method has one parameter of type Graphics. This
parameter contains the graphics context, which describes the
graphics environment in which the applet is running.
• Inside paint( ) is a call to drawString( ), which is a member of the
Graphics class. This method outputs a string beginning at the
specified X,Y location.
• Notice that the applet does not have a main( ) method. Unlike
Java programs, applets do not begin execution at main( ).
Instead, an applet begins execution when the name of its class is
passed to an applet viewer or to a network browser.
Applets
Compiling the applet is same as we have been compiling programs.
However, running SimpleApplet involves a different process.
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, appletviewer.
An applet viewer executes your applet in a window. This is
generally the fastest and easiest way to test your applet.
To execute an applet in a web browser, you need to write a short
HTML text file that contains a tag that loads the applet.
Here is the HTML file that executes SimpleApplet:
<applet code="SimpleApplet" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the
display area used by the applet. After you create this file, you can
execute your browser and then load this file, which causes
SimpleApplet to be executed.
Applets
To execute SimpleApplet with an applet viewer, we may also execute the
HTML file shown earlier. For example, if the preceding HTML file is called
RunApp.html, then the following command line will run SimpleApplet:
C:>appletviewer RunApp.html
A more convenient method
you can quickly iterate through applet development by using these three
steps:
1. Edit a Java source file.
2. Compile your program
3. Execute the applet viewer, specifying the name of your applet’s source
file. The applet viewer will encounter the APPLET tag within the comment
and execute your applet.
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
Applets
The window produced by SimpleApplet, as displayed by the applet
viewer is shown below.
Applet Architecture
An applet is a window-based program and applets are event driven
An Applet Skeleton
All but the most trivial applets override a set of methods that
provides the basic mechanism by which the browser or applet
viewer interfaces to the applet and controls its execution. Four of
these methods, init( ), start( ), stop( ), and destroy( ), apply to all
applets and are defined by Applet.
Two Types of Applets
1. The first type of applets uses the Abstract Window Toolkit (AWT)
to provide the graphic user interface.
2. The second types of applets are those based on the Swing class
JApplet. Swing applets use the Swing classes to provide the GUI.
Applet Architecture
// An Applet skeleton.
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
}
}
Applet Architecture
When the above applet code is run, it generates the following window when
viewed with an applet viewer:
Applet Architecture
Applet Initialization and Termination
It is important to understand the order in which the various methods
shown in the skeleton are called.
When an applet begins, the following methods are called, 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. destroy( )
Applet Architecture
Applet Initialization and Termination
init( )
The init( ) method is the first method to be called. This is where we should
initialize variables. This method is called only once during the run time of your
applet.
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped. Whereas init( ) is called once—the first time an applet is
loaded—start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes
execution at start( ).
paint( )
The paint( ) method is called each time your applet’s output must be redrawn.
This situation can occur for several reasons. For example, the window in which the
applet is running may be overwritten by another window and then uncovered. Or
the applet window may be minimized and then restored. paint( ) is also called
when the applet begins execution.
Applet Architecture
Applet Initialization and Termination
stop( )
The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is
called, the applet is probably running. We should use stop( ) to suspend threads
that don’t need to run when the applet is not visible. We can restart them when
start( ) is called if the user returns to the page.
destroy( )
The destroy( ) method is called when the environment determines that our applet
needs to be removed completely from memory. At this point, we should free up
any resources the applet may be using. The stop( ) method is always called before
destroy( ).
Applet Architecture
Applet Initialization and Termination
To set the background color of an applet’s window, use setBackground( ). To set
the foreground color, use setForeground( ). These methods are defined by
Component, and they have the following general forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
The class Color defines the constants shown herethat can be used to specify
colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
Applet Architecture
The following example sets the background color to green and the
text color to red:
setBackground(Color.green);
setForeground(Color.red);
You can obtain the current settings for the background and
foreground colors by calling getBackground( ) and getForeground( ),
respectively.
Here is a very simple applet that sets the background color to cyan,
the foreground color to red, and displays a message that illustrates
the order in which the init( ), start( ), and paint( ) methods are called
when an applet starts up:
Applet Architecture
/* A simple applet that sets the
foreground and
background colors and outputs a
string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample"
width=300 height=50>
</applet>
*/
public class Sample extends
Applet{
String msg;
// set the foreground and
background colors.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be
displayed.
public void start() {
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
Applet Architecture
/* A simple applet that sets the foreground and background colors
and outputs a string. */
This applet generates the window shown here:
The methods stop( ) and destroy( ) are not overridden, because
they are not needed by this simple applet
Applets
Requesting Repainting
How can the applet itself cause its window to be updated when its
information changes? For example, if an applet is displaying a moving
banner, what mechanism does the applet use to update the window each
time this banner scrolls?
Whenever an applet needs to update the information displayed in its
window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT. It causes the AWT run-time
system to execute a call to your applet’s update( ) method, which, in its
default implementation, calls paint( ). For example, if part of your applet
needs to output a string, it can store this string in a String variable and
then call repaint( ). Inside paint( ), you will output the string using
drawString( ).
The repaint( ) method has the following general forms –
void repaint( ) - This version causes the entire window to be repainted
The following version specifies a region that will be repainted
void repaint(int left, int top, int width, int height)
Applets
A Simple Banner Applet
This applet scrolls a message, from right to left, across the applet’s
window. Since the scrolling of the message is a repetitive task, it is
performed by a separate thread, created by the applet when it is
initialized.
/* A simple banner applet. This applet creates a thread that scrolls
the message contained in msg right to left across the applet's
window.*/
Applets
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
public class SimpleBanner extends Applet implements
Runnable {
String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
// Set colors and initialize thread.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner.
public void run() {
char ch;
// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}
}
// Pause the banner.
public void stop() {
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}
}
Applets
output
Passing Parameters to Applets
To retrieve a parameter, use the getParameter( ) method. It returns
the value of the specified parameter in the form of a String object.
Thus, for numeric and boolean values, we need to convert their
string representations into their internal formats.
Passing Parameters to Applets
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}
Passing Parameters to Applets
output
A Simple Swing Application
// A simple Swing application.
import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing
Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user
closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_
ON_CLOSE);
// Create a text-based label.
JLabel jlab = new JLabel(" Swing means
powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching
thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
javac SwingDemo.java
To run the program, use this command line:
java SwingDemo
A Simple Swing Application
Output
• The program begins by importing javax.swing, which defines classes that
implement labels, buttons, text controls, and menus.
• A container called jfrm defines a rectangular window complete with a title
bar; close, minimize, maximize, and restore buttons; and a system menu.
Thus, it creates a standard, top-level window.
• The setSize( ) method (which is inherited by JFrame from the AWT class
Component) sets the dimensions of the window, which are specified in
pixels.
A Simple Swing Application
• By default, when a top-level window is closed, the window is removed from
the screen, but the application is not terminated.
• We usually want the entire application to terminate when its top-level
window is closed. The easiest way to achieve this is to call
setDefaultCloseOperation( ), as the program does:
• jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• The next line of code creates a Swing JLabel component:
• JLabel jlab = new JLabel(" Swing means powerful GUIs.");
• The next line of code adds the label to the content pane of the frame:
• jfrm.add(jlab);
• All top-level containers have a content pane in which components are stored.
Thus, to add a component to a frame, you must add it to the frame’s content
pane. This is accomplished by calling add( ) on the JFrame reference (jfrm in
this case).
• The last statement in the SwingDemo constructor causes the window to
become visible: jfrm.setVisible(true);
A Simple Swing Application
Inside main( ), a SwingDemo object is created, which causes the window and the
label to be displayed. SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
This sequence causes a SwingDemo object to be created on the event dispatching
thread rather than on the main thread of the application.

More Related Content

What's hot

Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environmentmuthusvm
 
Accessible custom radio buttons and checkboxes
Accessible custom radio buttons and checkboxesAccessible custom radio buttons and checkboxes
Accessible custom radio buttons and checkboxesRuss Weakley
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) APImuthusvm
 
Publication Non Visual Components
Publication Non Visual ComponentsPublication Non Visual Components
Publication Non Visual Componentssatyres
 
Tutorials3
Tutorials3Tutorials3
Tutorials3raja umair
 
Creating an Accessible button dropdown
Creating an Accessible button dropdownCreating an Accessible button dropdown
Creating an Accessible button dropdownRuss Weakley
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid drawinfo_zybotech
 

What's hot (8)

Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environment
 
Accessible custom radio buttons and checkboxes
Accessible custom radio buttons and checkboxesAccessible custom radio buttons and checkboxes
Accessible custom radio buttons and checkboxes
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) API
 
Publication Non Visual Components
Publication Non Visual ComponentsPublication Non Visual Components
Publication Non Visual Components
 
Android-dialogs in android-chapter14
Android-dialogs in android-chapter14Android-dialogs in android-chapter14
Android-dialogs in android-chapter14
 
Tutorials3
Tutorials3Tutorials3
Tutorials3
 
Creating an Accessible button dropdown
Creating an Accessible button dropdownCreating an Accessible button dropdown
Creating an Accessible button dropdown
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 

Similar to Java lab lecture 2

Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awtvishal choudhary
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)Asim Rais Siddiqui
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swingsJafar Nesargi
 
Ch12. graphical user interfaces
Ch12. graphical user interfacesCh12. graphical user interfaces
Ch12. graphical user interfacesArslan Karamat
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Javayht4ever
 
ITE 1122_ AWT and SWING.pptx
ITE 1122_ AWT  and SWING.pptxITE 1122_ AWT  and SWING.pptx
ITE 1122_ AWT and SWING.pptxudithaisur
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC StructureDipika Wadhvani
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swingbackdoor
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FXpratikkadam78
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
Ajp notes-chapter-02
Ajp notes-chapter-02Ajp notes-chapter-02
Ajp notes-chapter-02Ankit Dubey
 
HCI 3e - Ch 8: Implementation support
HCI 3e - Ch 8:  Implementation supportHCI 3e - Ch 8:  Implementation support
HCI 3e - Ch 8: Implementation supportAlan Dix
 
java presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swingsjava presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on SwingsMohanYedatkar
 

Similar to Java lab lecture 2 (20)

Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awt
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
Advanced swing
Advanced swingAdvanced swing
Advanced swing
 
Swift
SwiftSwift
Swift
 
Ch12. graphical user interfaces
Ch12. graphical user interfacesCh12. graphical user interfaces
Ch12. graphical user interfaces
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
ITE 1122_ AWT and SWING.pptx
ITE 1122_ AWT  and SWING.pptxITE 1122_ AWT  and SWING.pptx
ITE 1122_ AWT and SWING.pptx
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC Structure
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swing
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FX
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Ajp notes-chapter-02
Ajp notes-chapter-02Ajp notes-chapter-02
Ajp notes-chapter-02
 
HCI 3e - Ch 8: Implementation support
HCI 3e - Ch 8:  Implementation supportHCI 3e - Ch 8:  Implementation support
HCI 3e - Ch 8: Implementation support
 
GUI.pdf
GUI.pdfGUI.pdf
GUI.pdf
 
java presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swingsjava presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swings
 

More from vishal choudhary

SE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptSE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptvishal choudhary
 
SE-coupling and cohesion.ppt
SE-coupling and cohesion.pptSE-coupling and cohesion.ppt
SE-coupling and cohesion.pptvishal choudhary
 
SE-software design.ppt
SE-software design.pptSE-software design.ppt
SE-software design.pptvishal choudhary
 
Multimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptxMultimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptxvishal choudhary
 
MultimediaLecture5.pptx
MultimediaLecture5.pptxMultimediaLecture5.pptx
MultimediaLecture5.pptxvishal choudhary
 
Multimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptxMultimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptxvishal choudhary
 
MultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptxMultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptxvishal choudhary
 
Multimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptxMultimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptxvishal choudhary
 
Multimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptxMultimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptxvishal choudhary
 

More from vishal choudhary (20)

SE-Lecture1.ppt
SE-Lecture1.pptSE-Lecture1.ppt
SE-Lecture1.ppt
 
SE-Testing.ppt
SE-Testing.pptSE-Testing.ppt
SE-Testing.ppt
 
SE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptSE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.ppt
 
SE-Lecture-7.pptx
SE-Lecture-7.pptxSE-Lecture-7.pptx
SE-Lecture-7.pptx
 
Se-Lecture-6.ppt
Se-Lecture-6.pptSe-Lecture-6.ppt
Se-Lecture-6.ppt
 
SE-Lecture-5.pptx
SE-Lecture-5.pptxSE-Lecture-5.pptx
SE-Lecture-5.pptx
 
XML.pptx
XML.pptxXML.pptx
XML.pptx
 
SE-Lecture-8.pptx
SE-Lecture-8.pptxSE-Lecture-8.pptx
SE-Lecture-8.pptx
 
SE-coupling and cohesion.ppt
SE-coupling and cohesion.pptSE-coupling and cohesion.ppt
SE-coupling and cohesion.ppt
 
SE-Lecture-2.pptx
SE-Lecture-2.pptxSE-Lecture-2.pptx
SE-Lecture-2.pptx
 
SE-software design.ppt
SE-software design.pptSE-software design.ppt
SE-software design.ppt
 
SE1.ppt
SE1.pptSE1.ppt
SE1.ppt
 
SE-Lecture-4.pptx
SE-Lecture-4.pptxSE-Lecture-4.pptx
SE-Lecture-4.pptx
 
SE-Lecture=3.pptx
SE-Lecture=3.pptxSE-Lecture=3.pptx
SE-Lecture=3.pptx
 
Multimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptxMultimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptx
 
MultimediaLecture5.pptx
MultimediaLecture5.pptxMultimediaLecture5.pptx
MultimediaLecture5.pptx
 
Multimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptxMultimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptx
 
MultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptxMultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptx
 
Multimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptxMultimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptx
 
Multimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptxMultimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptx
 

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)Dr. Mazin Mohamed alkathiri
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Java lab lecture 2

  • 1. Introduction to Applets, Swing & MVC Architecture Advanced Java Lab
  • 2. Introduction to Swing (Java’s GUI Components) Introduction to Swing GUI programming involves a computational model known as event-driven programming, which means that GUI programs react to events that are generated mostly by the user’s interactions with elements in the GUI. Java’s GUI Components The Java library comes with two separate but interrelated packages of GUI components, the older java.awt package and the newer javax.swing package. For the most part, the Swing classes supersede the AWT classes. For example, the java.awt.Button class is superseded by the javax.swing.JButton class, and the java.awt.TextField class is superseded by the javax.swing.JTextField class.
  • 3. Swing V/S AWT The Swing classes are generally considered to be superior to their AWT counterparts. For one thing, Swing components use a sophisticated object-oriented design known as the model-view-controller (MVC) architecture, which gives them much greater functionality than their AWT counterparts. For example, whereas an AWT Button can only have a string as its label, a Swing JButton can use an image as a label. Second, Swing components are written entirely in Java which makes them more portable and enables them to behave the same way regardless of the operating system on which they are run. AWT components are called heavyweight because they depend on the native (peer) system for their drawing and rendering. Because of their portability, Swing components are considered lightweight. The Swing GUI components are part of the Java Foundation Classes (JFC), a collection of classes that do not depend as much on the underlying platform.
  • 4. Swing V/S AWT The above figure shows that the top-level Swing classes—the JApplet, JDialog, JFrame, and JWindow—are direct subclasses of their corresponding AWT counterparts. The remaining Swing components (Fig. 2, below) are subclasses of java.awt.Component and java.awt.Container.
  • 6. Swing V/S AWT • It is important to note that the Swing based GUIs are still dependent on the AWT. Java programs need to have some way to map their windows to the windowing system used on the native (Windows, Unix, or Macintosh) platform. • The AWT’s top-level windows—Window, Frame, Dialog, and Panel— provide that mapping. • Also, the JComponent class, which is the basis for all Swing components, is derived from java.awt.Container. • Finally, all GUI applications and applets use layout managers (java.- awt.FlowLayout), fonts (java.awt.Font), colors ( java.awt.Color), and other non-component classes that are defined in the AWT. • There is just no way to design a GUI without using AWT classes
  • 7. The Swing Component Set Java’s Swing components are defined in a collection of packages named javax.swing.*. Swing packages include the following: javax.swing.event.∗ javax.swing.text.∗ javax.swing.plaf.∗ The javax.swing.event package defines the various Swing events and their listeners, such as the MenuEvent and the MenuListener. (In the AWT, the AWT events and listeners were defined in java.awt.event.) The javax.swing.text package contains the classes for JTextField and JTextComponent. The javax.swing.plaf package contains Swing’s look-and-feel classes. The term plaf is an acronym for pluggable look and feel. Swing’s platform-independent look and feel is achieved by placing all the code responsible for drawing a component in a class that is separate from the component itself. For example, in addition to JButton, the class that defines the button control, there will be a separate class responsible for drawing the button on the screen. The drawing class will control the button’s color, shape, and other characteristics of its appearance.
  • 8. Model-View-Controller Architecture Java’s Swing components have been implemented using an object oriented design known as the model-view-controller (MVC) model. Any Swing component can be considered in terms of three independent aspects: what state it’s in (its model), how it looks (its view), and what it does (its controller). Model The model encompasses the state data for each component. For example, the model of a scrollbar component might contain information about the current position of its adjustable “thumb,” its minimum and maximum values, and the thumb’s width (relative to the range of values). A menu, on the other hand, may simply contain a list of the menu items the user can select from.
  • 9. Model-View-Controller Architecture View The view refers to how we see the component on the screen. For example consider an application window on two different GUI platforms. Almost all window frames will have a titlebar spanning the top of the window. However, the titlebar may have a close box on the left side (like the older MacOS platform), or it may have the close box on the right side (as in the Windows platform). These are examples of different types of views for the same window object. Controller The controller is the portion of the user interface that dictates how the component interacts with events. Events come in many forms - a mouse click, gaining or losing focus, a keyboard event that triggers a specific menu command, or even a directive to repaint part of the screen. The controller decides how each component will react to the event-if it reacts at all.
  • 10. Model-View-Controller Architecture Example-1 For example, a button’s role is to appear on the interface waiting to be clicked. When it is clicked, the button’s appearance changes. It looks pushed in or it changes color briefly, and then it changes back to its original (unclicked) appearance. In the MVC model, this aspect of the button is its view. Whether a button is enabled or disabled and whether it is pressed or not are properties of its internal state. Such properties constitute the button’s model. So we can say that, a button’s view—how it looks— depends on its model. Because a button’s state will change when it is clicked or when it is enabled by the program, some object needs to keep track of these changes. That part of the component is its controller. Figure-3 shows how the button’s model, view, and controller interact with each other.
  • 11. Model-View-Controller Architecture Figure-3 shows how the button’s model, view, and controller interact with each other. The model-view-controller architecture
  • 12. Model-View-Controller Architecture Suppose the user clicks the button. This action is detected by the controller. Whenever the mouse button is pressed, the controller tells the model to change into the pressed state. The model, in turn, generates an event that is passed to the view. The event tells the view that the button needs to be redrawn to reflect its change in state. When the mouse button is released, a similar sequence of events occurs. The model is told to change to the unpressed state. It in turn generates an event, handled by the view, which changes the button’s appearance.
  • 13. Model-View-Controller Architecture Example-2 The following figure-4 shows, how the model, view, and controller work together to create a scrollbar component
  • 14. Model-View-Controller Architecture Example-2 The scrollbar uses the information in the model to determine how far into the scrollbar to render the thumb and how wide the thumb should be. Note that the model specifies this information relative to the minimum and the maximum. It does not give the position or width of the thumb in screen pixels—the view calculates that. The view determines exactly where and how to draw the scrollbar, given the proportions offered by the model. The view knows whether it is a horizontal or vertical scrollbar, and it knows exactly how to shadow the end buttons and the thumb. Finally, the controller is responsible for handling mouse events on the component. The controller knows, for example, that dragging the thumb is a legitimate action for a scroll bar, and pushing on the end buttons is acceptable as well.
  • 15. Model-View-Controller Architecture Example-2 The scrollbar uses the information in the model to determine how far into the scrollbar to render the thumb and how wide the thumb should be. Note that the model specifies this information relative to the minimum and the maximum. It does not give the position or width of the thumb in screen pixels—the view calculates that. The view determines exactly where and how to draw the scrollbar, given the proportions offered by the model. The view knows whether it is a horizontal or vertical scrollbar, and it knows exactly how to shadow the end buttons and the thumb. Finally, the controller is responsible for handling mouse events on the component. The controller knows, for example, that dragging the thumb is a legitimate action for a scroll bar, and pushing on the end buttons is acceptable as well.
  • 16. Applets Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document. After an applet arrives on the client, it has limited access to resources so that it can produce a graphical user interface and run complex computations without introducing the risk of viruses or breaching data integrity. A simple applet import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } }
  • 17. Applets • Applets interact with the user through the AWT, not through the console-based I/O classes. The second import statement imports the applet package, which contains the class Applet. Every applet that we create must be a subclass of Applet. • The SimpleApplet class is public because it will be accessed by code that is outside the program. • Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet. • paint( ) is called each time that the applet must redisplay its output. • This situation can occur for several reasons. For example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the applet window can be minimized and then restored. • paint( ) is also called when the applet begins execution.
  • 18. Applets • The paint( ) method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. • Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. • Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main( ). Instead, an applet begins execution when the name of its class is passed to an applet viewer or to a network browser.
  • 19. Applets Compiling the applet is same as we have been compiling programs. However, running SimpleApplet involves a different process. 1. Executing the applet within a Java-compatible web browser. 2. Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet. To execute an applet in a web browser, you need to write a short HTML text file that contains a tag that loads the applet. Here is the HTML file that executes SimpleApplet: <applet code="SimpleApplet" width=200 height=60> </applet> The width and height statements specify the dimensions of the display area used by the applet. After you create this file, you can execute your browser and then load this file, which causes SimpleApplet to be executed.
  • 20. Applets To execute SimpleApplet with an applet viewer, we may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet: C:>appletviewer RunApp.html A more convenient method you can quickly iterate through applet development by using these three steps: 1. Edit a Java source file. 2. Compile your program 3. Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute your applet. import java.awt.*; import java.applet.*; /* <applet code="SimpleApplet" width=200 height=60> </applet> */
  • 21. Applets The window produced by SimpleApplet, as displayed by the applet viewer is shown below.
  • 22. Applet Architecture An applet is a window-based program and applets are event driven An Applet Skeleton All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. Two Types of Applets 1. The first type of applets uses the Abstract Window Toolkit (AWT) to provide the graphic user interface. 2. The second types of applets are those based on the Swing class JApplet. Swing applets use the Swing classes to provide the GUI.
  • 23. Applet Architecture // An Applet skeleton. 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 } }
  • 24. Applet Architecture When the above applet code is run, it generates the following window when viewed with an applet viewer:
  • 25. Applet Architecture Applet Initialization and Termination It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the following methods are called, 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. destroy( )
  • 26. Applet Architecture Applet Initialization and Termination init( ) The init( ) method is the first method to be called. This is where we should initialize variables. This method is called only once during the run time of your applet. start( ) The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ). paint( ) The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution.
  • 27. Applet Architecture Applet Initialization and Termination stop( ) The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. We should use stop( ) to suspend threads that don’t need to run when the applet is not visible. We can restart them when start( ) is called if the user returns to the page. destroy( ) The destroy( ) method is called when the environment determines that our applet needs to be removed completely from memory. At this point, we should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).
  • 28. Applet Architecture Applet Initialization and Termination To set the background color of an applet’s window, use setBackground( ). To set the foreground color, use setForeground( ). These methods are defined by Component, and they have the following general forms: void setBackground(Color newColor) void setForeground(Color newColor) The class Color defines the constants shown herethat can be used to specify colors: Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.red Color.gray Color.white Color.green Color.yellow Color.lightGray
  • 29. Applet Architecture The following example sets the background color to green and the text color to red: setBackground(Color.green); setForeground(Color.red); You can obtain the current settings for the background and foreground colors by calling getBackground( ) and getForeground( ), respectively. Here is a very simple applet that sets the background color to cyan, the foreground color to red, and displays a message that illustrates the order in which the init( ), start( ), and paint( ) methods are called when an applet starts up:
  • 30. Applet Architecture /* A simple applet that sets the foreground and background colors and outputs a string. */ import java.awt.*; import java.applet.*; /* <applet code="Sample" width=300 height=50> </applet> */ public class Sample extends Applet{ String msg; // set the foreground and background colors. public void init() { setBackground(Color.cyan); setForeground(Color.red); msg = "Inside init( ) --"; } // Initialize the string to be displayed. public void start() { msg += " Inside start( ) --"; } // Display msg in applet window. public void paint(Graphics g) { msg += " Inside paint( )."; g.drawString(msg, 10, 30); } }
  • 31. Applet Architecture /* A simple applet that sets the foreground and background colors and outputs a string. */ This applet generates the window shown here: The methods stop( ) and destroy( ) are not overridden, because they are not needed by this simple applet
  • 32. Applets Requesting Repainting How can the applet itself cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? Whenever an applet needs to update the information displayed in its window, it simply calls repaint( ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet’s update( ) method, which, in its default implementation, calls paint( ). For example, if part of your applet needs to output a string, it can store this string in a String variable and then call repaint( ). Inside paint( ), you will output the string using drawString( ). The repaint( ) method has the following general forms – void repaint( ) - This version causes the entire window to be repainted The following version specifies a region that will be repainted void repaint(int left, int top, int width, int height)
  • 33. Applets A Simple Banner Applet This applet scrolls a message, from right to left, across the applet’s window. Since the scrolling of the message is a repetitive task, it is performed by a separate thread, created by the applet when it is initialized. /* A simple banner applet. This applet creates a thread that scrolls the message contained in msg right to left across the applet's window.*/
  • 34. Applets import java.awt.*; import java.applet.*; /* <applet code="SimpleBanner" width=300 height=50> </applet> */ public class SimpleBanner extends Applet implements Runnable { String msg = " A Simple Moving Banner."; Thread t = null; int state; boolean stopFlag; // Set colors and initialize thread. public void init() { setBackground(Color.cyan); setForeground(Color.red); } // Start thread public void start() { t = new Thread(this); stopFlag = false; t.start(); } // Entry point for the thread that runs the banner. public void run() { char ch; // Display banner for( ; ; ) { try { repaint(); Thread.sleep(250); ch = msg.charAt(0); msg = msg.substring(1, msg.length()); msg += ch; if(stopFlag) break; } catch(InterruptedException e) {} } } // Pause the banner. public void stop() { stopFlag = true; t = null; } // Display the banner. public void paint(Graphics g) { g.drawString(msg, 50, 30); } }
  • 36. Passing Parameters to Applets To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values, we need to convert their string representations into their internal formats.
  • 37. Passing Parameters to Applets // Use Parameters import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ public class ParamDemo extends Applet{ String fontName; int fontSize; float leading; boolean active; // Initialize the string to be displayed. public void start() { String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter("fontSize"); try { if(param != null) // if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) { fontSize = -1; } param = getParameter("leading"); try { if(param != null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; } catch(NumberFormatException e) { leading = -1; } param = getParameter("accountEnabled"); if(param != null) active = Boolean.valueOf(param).booleanValue(); } // Display parameters. public void paint(Graphics g) { g.drawString("Font name: " + fontName, 0, 10); g.drawString("Font size: " + fontSize, 0, 26); g.drawString("Leading: " + leading, 0, 42); g.drawString("Account Active: " + active, 0, 58); } }
  • 38. Passing Parameters to Applets output
  • 39. A Simple Swing Application // A simple Swing application. import javax.swing.*; class SwingDemo { SwingDemo() { // Create a new JFrame container. JFrame jfrm = new JFrame("A Simple Swing Application"); // Give the frame an initial size. jfrm.setSize(275, 100); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ ON_CLOSE); // Create a text-based label. JLabel jlab = new JLabel(" Swing means powerful GUIs."); // Add the label to the content pane. jfrm.add(jlab); // Display the frame. jfrm.setVisible(true); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new SwingDemo(); } }); } } javac SwingDemo.java To run the program, use this command line: java SwingDemo
  • 40. A Simple Swing Application Output • The program begins by importing javax.swing, which defines classes that implement labels, buttons, text controls, and menus. • A container called jfrm defines a rectangular window complete with a title bar; close, minimize, maximize, and restore buttons; and a system menu. Thus, it creates a standard, top-level window. • The setSize( ) method (which is inherited by JFrame from the AWT class Component) sets the dimensions of the window, which are specified in pixels.
  • 41. A Simple Swing Application • By default, when a top-level window is closed, the window is removed from the screen, but the application is not terminated. • We usually want the entire application to terminate when its top-level window is closed. The easiest way to achieve this is to call setDefaultCloseOperation( ), as the program does: • jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • The next line of code creates a Swing JLabel component: • JLabel jlab = new JLabel(" Swing means powerful GUIs."); • The next line of code adds the label to the content pane of the frame: • jfrm.add(jlab); • All top-level containers have a content pane in which components are stored. Thus, to add a component to a frame, you must add it to the frame’s content pane. This is accomplished by calling add( ) on the JFrame reference (jfrm in this case). • The last statement in the SwingDemo constructor causes the window to become visible: jfrm.setVisible(true);
  • 42. A Simple Swing Application Inside main( ), a SwingDemo object is created, which causes the window and the label to be displayed. SwingUtilities.invokeLater(new Runnable() { public void run() { new SwingDemo(); } }); This sequence causes a SwingDemo object to be created on the event dispatching thread rather than on the main thread of the application.