0% found this document useful (0 votes)
99 views42 pages

Introduction To Applets, Swing & MVC Architecture: Advanced Java Lab

The document discusses Java's Swing GUI components and the model-view-controller (MVC) architecture. It explains that Swing components are superior to AWT components because they use MVC, which gives greater functionality. It also describes how MVC separates a component into independent model, view, and controller aspects. The model stores state data, the view handles display, and the controller manages events and user interactions. Examples of how MVC applies to buttons and scrollbars are provided. The document also provides a brief introduction to Java applets.

Uploaded by

Vishal Choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
99 views42 pages

Introduction To Applets, Swing & MVC Architecture: Advanced Java Lab

The document discusses Java's Swing GUI components and the model-view-controller (MVC) architecture. It explains that Swing components are superior to AWT components because they use MVC, which gives greater functionality. It also describes how MVC separates a component into independent model, view, and controller aspects. The model stores state data, the view handles display, and the controller manages events and user interactions. Examples of how MVC applies to buttons and scrollbars are provided. The document also provides a brief introduction to Java applets.

Uploaded by

Vishal Choudhary
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 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
// An Applet skeleton.
Architecture
}
import java.awt.*; // Called when the applet is stopped.
import java.applet.*; public void stop() {
/* // suspends execution
<applet code="AppletSkel" width=300 }
height=100> /* Called when applet is terminated.
</applet> This is the last
*/ method executed. */
public class AppletSkel extends Applet { public void destroy() {
// Called first. // perform shutdown activities
public void init() { }
// initialization // Called when an applet's window must
} be restored.
/* Called second, after init(). Also called public void paint(Graphics g) {
whenever // redisplay contents of window
the applet is restarted. */ }
public void start() { }
// start or resume execution
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 setForeground(Color.red);
foreground and msg = "Inside init( ) --";
background colors and outputs a }
string. */ // Initialize the string to be
import java.awt.*; displayed.
import java.applet.*; public void start() {
/* msg += " Inside start( ) --";
<applet code="Sample" }
width=300 height=50> // Display msg in applet window.
</applet> public void paint(Graphics g) {
*/ msg += " Inside paint( ).";
public class Sample extends g.drawString(msg, 10, 30);
Applet{ }
String msg; }
// set the foreground and
background colors.
public void init() {
setBackground(Color.cyan);
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.*; // Display banner
import java.applet.*; for( ; ; ) {
/* try {
<applet code="SimpleBanner" width=300 height=50> repaint();
</applet> Thread.sleep(250);
*/ ch = msg.charAt(0);
public class SimpleBanner extends Applet implements msg = msg.substring(1, msg.length());
Runnable { msg += ch;
String msg = " A Simple Moving Banner."; if(stopFlag)
Thread t = null; break;
int state; } catch(InterruptedException e) {}
boolean stopFlag; }
// Set colors and initialize thread. }
public void init() { // Pause the banner.
setBackground(Color.cyan); public void stop() {
setForeground(Color.red); stopFlag = true;
} t = null;
// Start thread }
public void start() { // Display the banner.
t = new Thread(this); public void paint(Graphics g) {
stopFlag = false; g.drawString(msg, 50, 30);
t.start(); }
} }
// Entry point for the thread that runs the banner.
public void run() {
char ch;
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 else
import java.awt.*; fontSize = 0;
import java.applet.*; } catch(NumberFormatException e) {
/* fontSize = -1;
<applet code="ParamDemo" width=300 height=80> }
<param name=fontName value=Courier> param = getParameter("leading");
<param name=fontSize value=14> try {
<param name=leading value=2> if(param != null) // if not found
<param name=accountEnabled value=true> leading = Float.valueOf(param).floatValue();
</applet> else
*/ leading = 0;
public class ParamDemo extends Applet{ } catch(NumberFormatException e) {
String fontName; leading = -1;
int fontSize; }
float leading; param = getParameter("accountEnabled");
boolean active; if(param != null)
// Initialize the string to be displayed. active = Boolean.valueOf(param).booleanValue();
public void start() { }
String param; // Display parameters.
fontName = getParameter("fontName"); public void paint(Graphics g) {
if(fontName == null) g.drawString("Font name: " + fontName, 0, 10);
fontName = "Not Found"; g.drawString("Font size: " + fontSize, 0, 26);
param = getParameter("fontSize"); g.drawString("Leading: " + leading, 0, 42);
try { g.drawString("Account Active: " + active, 0, 58);
if(param != null) // if not found }
fontSize = Integer.parseInt(param); }
Passing Parameters to Applets
output
A Simple Swing Application
// A simple Swing application. jfrm.setVisible(true);
import javax.swing.*; }
class SwingDemo { public static void main(String args[]) {
SwingDemo() { // Create the frame on the event dispatching
// Create a new JFrame container. thread.
JFrame jfrm = new JFrame("A Simple Swing SwingUtilities.invokeLater(new Runnable() {
Application"); public void run() {
// Give the frame an initial size. new SwingDemo();
jfrm.setSize(275, 100); }
// Terminate the program when the user });
closes the application. }
jfrm.setDefaultCloseOperation(JFrame.EXIT_ }
ON_CLOSE); javac SwingDemo.java
// Create a text-based label. To run the program, use this command line:
JLabel jlab = new JLabel(" Swing means java SwingDemo
powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
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.

You might also like