SlideShare a Scribd company logo
Advanced Java Lab
Introduction to Applets, Swing &
MVC Architecture
Presented By: Vishal Choudhary
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
Swing V/S AWT-Abstract Window
Toolkit
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 Abstract Window Toolkit (AWT) is Java's original platform-
dependent windowing, graphics, and user-interface widget toolkit,
preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the
standard API for providing a graphical user interface (GUI) for a Java program.
AWT is also the GUI toolkit for a number of Java ME profiles. For
example, Connected Device Configuration profiles require
Java runtimes on mobile telephones to support the Abstract Window Toolkit.
Swing is a GUI widget toolkit for Java. It is part of Oracle's
Java Foundation Classes – an API for providing a graphical
user interface for Java programs. Swing was developed to
provide a more sophisticated set of GUI components than the
earlier Abstract Window Toolkit
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
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
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.
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
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
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.
Advanced java lab swing mvc awt
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,
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.
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.E
XIT_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.
Ad

More Related Content

What's hot (20)

ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Java rmi
Java rmiJava rmi
Java rmi
Tanmoy Barman
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
Flipkart
 
Java RMI
Java RMIJava RMI
Java RMI
Prajakta Nimje
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
Moutasm Tamimi
 
Inter thread communication
Inter thread communicationInter thread communication
Inter thread communication
subash andey
 
Spring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHatSpring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHat
Scholarhat
 
Alice 4
Alice 4Alice 4
Alice 4
Elian Maya
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
Kongu Engineering College, Perundurai, Erode
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Hitesh Kumar
 
UDA-Componentes RUP. Autocomplete
UDA-Componentes RUP. AutocompleteUDA-Componentes RUP. Autocomplete
UDA-Componentes RUP. Autocomplete
Ander Martinez
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
Hiranya Jayathilaka
 
Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
Sayantan Sur
 
Session Tracking in servlets
Session Tracking in servletsSession Tracking in servlets
Session Tracking in servlets
chauhankapil
 
CIS 1403 Lab 2- Data Types and Variables
CIS 1403 Lab 2- Data Types and VariablesCIS 1403 Lab 2- Data Types and Variables
CIS 1403 Lab 2- Data Types and Variables
Hamad Odhabi
 
Project management 02112009
Project management 02112009Project management 02112009
Project management 02112009
Manish Chaurasia
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
SAGARDAVE29
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
Flipkart
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
Moutasm Tamimi
 
Inter thread communication
Inter thread communicationInter thread communication
Inter thread communication
subash andey
 
Spring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHatSpring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHat
Scholarhat
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Hitesh Kumar
 
UDA-Componentes RUP. Autocomplete
UDA-Componentes RUP. AutocompleteUDA-Componentes RUP. Autocomplete
UDA-Componentes RUP. Autocomplete
Ander Martinez
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Session Tracking in servlets
Session Tracking in servletsSession Tracking in servlets
Session Tracking in servlets
chauhankapil
 
CIS 1403 Lab 2- Data Types and Variables
CIS 1403 Lab 2- Data Types and VariablesCIS 1403 Lab 2- Data Types and Variables
CIS 1403 Lab 2- Data Types and Variables
Hamad Odhabi
 
Project management 02112009
Project management 02112009Project management 02112009
Project management 02112009
Manish Chaurasia
 

Similar to Advanced java lab swing mvc awt (20)

Java lab lecture 2
Java  lab  lecture 2Java  lab  lecture 2
Java lab lecture 2
vishal choudhary
 
Java_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptxJava_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptx
lakhatariyajaimin09
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
Jafar Nesargi
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
Dr. SURBHI SAROHA
 
Advanced swing
Advanced swingAdvanced swing
Advanced swing
Thesis Scientist Private Limited
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swing
backdoor
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FX
pratikkadam78
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
TabassumMaktum
 
Creating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interfaceCreating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
Ch12. graphical user interfaces
Ch12. graphical user interfacesCh12. graphical user interfaces
Ch12. graphical user interfaces
Arslan Karamat
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
GUI.pdf
GUI.pdfGUI.pdf
GUI.pdf
AbuSufyan82
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
Asim Rais Siddiqui
 
ITE 1122_ AWT and SWING.pptx
ITE 1122_ AWT  and SWING.pptxITE 1122_ AWT  and SWING.pptx
ITE 1122_ AWT and SWING.pptx
udithaisur
 
Swift
SwiftSwift
Swift
Larry Ball
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
Ankit Dubey
 
GUI JAVA PROG ~hmftj
GUI  JAVA PROG ~hmftjGUI  JAVA PROG ~hmftj
GUI JAVA PROG ~hmftj
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
Ad

More from vishal choudhary (20)

Pixel to Percentage conversion Convert left and right padding of a div to per...
Pixel to Percentage conversion Convert left and right padding of a div to per...Pixel to Percentage conversion Convert left and right padding of a div to per...
Pixel to Percentage conversion Convert left and right padding of a div to per...
vishal choudhary
 
esponsive web design means that your website (
esponsive web design means that your website (esponsive web design means that your website (
esponsive web design means that your website (
vishal choudhary
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
data base connectivity in php using msql database
data base connectivity in php using msql databasedata base connectivity in php using msql database
data base connectivity in php using msql database
vishal choudhary
 
software evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall modelsoftware evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall model
vishal choudhary
 
software Engineering lecture on development life cycle
software Engineering lecture on development life cyclesoftware Engineering lecture on development life cycle
software Engineering lecture on development life cycle
vishal choudhary
 
strings in php how to use different data types in string
strings in php how to use different data types in stringstrings in php how to use different data types in string
strings in php how to use different data types in string
vishal choudhary
 
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
OPEN SOURCE WEB APPLICATION DEVELOPMENT  questionOPEN SOURCE WEB APPLICATION DEVELOPMENT  question
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
web performnace optimization using css minification
web performnace optimization using css minificationweb performnace optimization using css minification
web performnace optimization using css minification
vishal choudhary
 
web performance optimization using style
web performance optimization using styleweb performance optimization using style
web performance optimization using style
vishal choudhary
 
Data types and variables in php for writing and databse
Data types and variables in php for writing  and databseData types and variables in php for writing  and databse
Data types and variables in php for writing and databse
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
sofwtare standard for test plan it execution
sofwtare standard for test plan it executionsofwtare standard for test plan it execution
sofwtare standard for test plan it execution
vishal choudhary
 
Software test policy and test plan in development
Software test policy and test plan in developmentSoftware test policy and test plan in development
Software test policy and test plan in development
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
introduction to php and its uses in daily
introduction to php and its uses in dailyintroduction to php and its uses in daily
introduction to php and its uses in daily
vishal choudhary
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 
PHP introduction how to create and start php
PHP introduction how to create and start phpPHP introduction how to create and start php
PHP introduction how to create and start php
vishal choudhary
 
SE-Lecture1.ppt
SE-Lecture1.pptSE-Lecture1.ppt
SE-Lecture1.ppt
vishal choudhary
 
Pixel to Percentage conversion Convert left and right padding of a div to per...
Pixel to Percentage conversion Convert left and right padding of a div to per...Pixel to Percentage conversion Convert left and right padding of a div to per...
Pixel to Percentage conversion Convert left and right padding of a div to per...
vishal choudhary
 
esponsive web design means that your website (
esponsive web design means that your website (esponsive web design means that your website (
esponsive web design means that your website (
vishal choudhary
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
data base connectivity in php using msql database
data base connectivity in php using msql databasedata base connectivity in php using msql database
data base connectivity in php using msql database
vishal choudhary
 
software evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall modelsoftware evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall model
vishal choudhary
 
software Engineering lecture on development life cycle
software Engineering lecture on development life cyclesoftware Engineering lecture on development life cycle
software Engineering lecture on development life cycle
vishal choudhary
 
strings in php how to use different data types in string
strings in php how to use different data types in stringstrings in php how to use different data types in string
strings in php how to use different data types in string
vishal choudhary
 
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
OPEN SOURCE WEB APPLICATION DEVELOPMENT  questionOPEN SOURCE WEB APPLICATION DEVELOPMENT  question
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
web performnace optimization using css minification
web performnace optimization using css minificationweb performnace optimization using css minification
web performnace optimization using css minification
vishal choudhary
 
web performance optimization using style
web performance optimization using styleweb performance optimization using style
web performance optimization using style
vishal choudhary
 
Data types and variables in php for writing and databse
Data types and variables in php for writing  and databseData types and variables in php for writing  and databse
Data types and variables in php for writing and databse
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
sofwtare standard for test plan it execution
sofwtare standard for test plan it executionsofwtare standard for test plan it execution
sofwtare standard for test plan it execution
vishal choudhary
 
Software test policy and test plan in development
Software test policy and test plan in developmentSoftware test policy and test plan in development
Software test policy and test plan in development
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
introduction to php and its uses in daily
introduction to php and its uses in dailyintroduction to php and its uses in daily
introduction to php and its uses in daily
vishal choudhary
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 
PHP introduction how to create and start php
PHP introduction how to create and start phpPHP introduction how to create and start php
PHP introduction how to create and start php
vishal choudhary
 
Ad

Recently uploaded (20)

Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 

Advanced java lab swing mvc awt

  • 1. Advanced Java Lab Introduction to Applets, Swing & MVC Architecture Presented By: Vishal Choudhary
  • 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
  • 3. Swing V/S AWT-Abstract Window Toolkit 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.
  • 4. The Abstract Window Toolkit (AWT) is Java's original platform- dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support the Abstract Window Toolkit. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes – an API for providing a graphical user interface for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit
  • 5. 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.
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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.
  • 11. 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
  • 12. Model-View-Controller Architecture Figure-3 shows how the button’s model, view, and controller interact with each other. The model-view-controller architecture
  • 13. 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.
  • 14. Model-View-Controller Architecture Example-2 The following figure-4 shows, how the model, view, and controller work together to create a scrollbar component
  • 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
  • 16. 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.
  • 17. 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); } }
  • 18. 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.
  • 19. 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.
  • 21. 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,
  • 22. 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> */
  • 23. Applets The window produced by SimpleApplet, as displayed by the applet viewer is shown below.
  • 24. 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.
  • 25. 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 } }
  • 26. Applet Architecture When the above applet code is run, it generates the following window when viewed with an applet viewer:
  • 27. 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( )
  • 28. 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.
  • 29. 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( ).
  • 30. 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
  • 31. 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:
  • 32. 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. 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); } }
  • 33. 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
  • 34. 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)
  • 35. 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.*/
  • 36. 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); } }
  • 38. 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.
  • 39. 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); } }
  • 40. Passing Parameters to Applets output
  • 41. 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.E XIT_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
  • 42. 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.
  • 43. 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);
  • 44. 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.
  翻译: