Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

applets in java,features and its programs, Essays (university) of Java Programming

applets in java and its working. applets life cycle and features and few programs using applets and also swing.

Typology: Essays (university)

2018/2019

Uploaded on 10/31/2019

nayana-bg
nayana-bg 🇮🇳

1 document

1 / 36

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
5th Module[Applets]
Mangala KB,CSE,CITech Page 1
Applets
Applet is a small program that
can be placed on a web page
will be executed by the web browser
give web pages “dynamic content”.
Java Applets enable user interaction with GUI elements
Applets are Java programs that can be embedded in HTML documents
When browser loads Web page containing applet,Applet downloads into
Web browser and begins execution or applets can be executed in
appletviewer.
Applets are not stand alone programs.
Applets are specified in html document by using applet tag
/* <applet code=MyApplet width=200 height=100>
</applet> */
[thus applet will be executed in java enabled web browser when it encounters
applet tag within the html file.]
The Applet class
Applet class provides all necessary methods to start and stop the applet
program.
It also provides methods to load and display images,and play audio clips.
Applet extends the AWT class Panel.
Panel extends Container which extends Component
Method Description
void destroy( ) Called by the browser just before an applet is terminated.
Your applet will override this method if it needs to perform
any cleanup prior to its destruction.
AccessibleContext
getAccessibleContext( ) Returns the accessibility context for the invoking object.
AppletContext getAppletContext( ) Returns the context associated with the applet.
String getAppletInfo( ) Returns a string that describes the applet.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio
clip found at the location specified by url.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24

Partial preview of the text

Download applets in java,features and its programs and more Essays (university) Java Programming in PDF only on Docsity!

Applets  Applet is a small program that  can be placed on a web page  will be executed by the web browser  give web pages “dynamic content”.  Java Applets enable user interaction with GUI elements  Applets are Java programs that can be embedded in HTML documents  When browser loads Web page containing applet,Applet downloads into Web browser and begins execution or applets can be executed in appletviewer.  Applets are not stand alone programs.  Applets are specified in html document by using applet tag  /* */  [thus applet will be executed in java enabled web browser when it encounters applet tag within the html file.]  The Applet class  Applet class provides all necessary methods to start and stop the applet program.  It also provides methods to load and display images,and play audio clips.  Applet extends the AWT class Panel.  Panel extends Container which extends Component Method Description void destroy( ) Called by the browser just before an applet is terminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction. AccessibleContext getAccessibleContext( ) Returns the accessibility context for the invoking object. AppletContext getAppletContext( ) Returns the context associated with the applet. String getAppletInfo( ) Returns a string that describes the applet. AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url.

Method Description AudioClip getAudioClip( URL url, String clipName) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url and having the name specified by clipName. URL getCodeBase( ) Returns the URL associated with the invoking applet. URL getDocumentBase( ) Returns the URL of the HTML document that invokes the applet. Image getImage(URL url) Returns an Image object that encapsulates the image found at the location specified by url. Image getImage( URL url, String imageName) Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName. Locale getLocale( ) Returns a Locale object that is used by various localesensitive classes and methods. String getParameter( String paramName) Returns the parameter associated with paramName. null is returned if the specified parameter is not found. String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parameters recognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose. void init( ) Called when an applet begins execution. It is the first method called for any applet. boolean isActive( ) Returns true if the applet has been started. It returns false if the applet has been stopped. static final AudioClip newAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. This method is similar to getAudioClip( ) except that it is static and can be executed without the need for an Applet object.

 the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond.  For example, when the user clicks the mouse inside the applet’s window, a mouse- clicked event is generated.  If the user presses a key while the applet’s window has input focus, a keypress event is generated.  Applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated.  An Applet Skeleton.  It defines init(),start(),stop(),destroy() methods  AWT-based applets will override paint() method defined by AWT Component class.This method is called when applet’s output must be redisplayed. import java.awt.; import java.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 } } When run, it generates the following window when viewed with an applet viewe

Applet Initialization and Termination  Applet methods are called in the following order  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( )

. init( )  The init( ) method is the first method to be called. Initialization of variables is done here. This method is called only once during the run time of 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 when applet’s output must be redrawn.  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. Whatever the cause, whenever the applet must redraw its output, paint( ) is called.  The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. 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. stop( ) is called,when the applet is probably running. stop( )is used to suspend threads that don’t need to run when the applet is not visible.

 They are also defined by Component ,they are: Color getBackground( ) Color getForeground( )  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: /* A simple applet that sets the foreground and background colors and outputs a string. / import java.awt.; import java.applet.; / */ public class Sample extends Applet { String msg; // set the foreground and background colors. public void init() { setBackground(Color.cyan); setForeground(Color.red); msg = "Inside init( ) --"; } // Initialize the string to be displayed. public void start() { msg += " Inside start( ) --"; 0 } // Display msg in applet window. public void paint(Graphics g) { msg += " Inside paint( )."; g.drawString(msg, 10, 30); } } This applet generates the window shown here: The methods stop( ) and destroy( ) are not overridden, because they are not needed by this simple applet

Requesting Repainting  As a general rule, an applet writes to its window only when its update( ) or paint( ) method is called by the AWT.  An applet must quickly return control to the run-time system.(constraint)  It cannot create a loop inside paint( ) that repeatedly scrolls the banner. This would prevent control from passing back to the AWT.  If applet needs to update the information displayed in the 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 by default, calls paint( ).  The AWT will then execute a call to paint( ), which can display the stored information.  The repaint( ) method has four forms. The simplest version of repaint( ) is shown here: 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)  These dimensions are specified in pixels.  Update may not be called immediately if system is slow or busy. In this case the following forms of repaint( ) are used:  void repaint(long maxDelay)  void repaint(long maxDelay, int x, int y, int width, int height)  Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called.  It is possible for a method other than paint( ) or update( ) to output to applet window,to do so it must obtain a graphics context by calling getGraphics( ) (defined by Component) and then use this context to output to the window.  A Simple Banner Applet  To demonstrate repaint( ), a simple banner applet is developed. This applet scrolls a message, from right to left, across the applet’s window.  The scrolling of the message is a repetitive task, it is performed by a separate thread, created by the applet when it is initialized. import java.awt.; import java.applet.; /* */ public class SimpleBanner extends Applet implements Runnable { String msg = " A Simple Moving Banner.";

stopFlag = true; t = null; } // Display the banner. public void paint(Graphics g) { g.drawString(msg, 50, 30); } }  SimpleBanner extends Applet and implements Runnable Interface.  It is necessary to implement Runnable interface since the applet will be creating a second thread of execution that will be used to scroll the banner.  Inside init( ), the foreground and background colors of the applet are set.  After initialization, the run-time system calls start( ) to start the applet running.  Inside start( ), a new thread of execution is created and assigned to the Thread variable t.  Then, the boolean variable stopFlag, which controls the execution of the applet, is set to false.  the thread is started by a call to t.start( ).  t.start( ) calls run( ) to begin executing.  Inside run( ), the characters in the string contained in msg are repeatedly rotated left.  Between each rotation, a call to repaint( ) is made. This eventually causes the paint( ) method to be called, and the current contents of msg are displayed.  Between each iteration, run( ) sleeps for a quarter of a second.  The stopFlag variable is checked on each iteration. When it is true, the run( ) method terminates.  If a browser is displaying the applet when a new page is viewed, the stop( ) method is called, which sets stopFlag to true, causing run( ) to terminate.

Using the Status Window  An applet can also output a message to the status window of the browser or applet viewer on which it is running.  showStatus( ) method displays the msg in the status window which is passed as a parameter to it.  The following applet demonstrates showStatus( ): // Using the Status Window. import java.awt.; import java.applet.; /* */ public class StatusWindow extends Applet { public void init() { setBackground(Color.cyan); } // Display msg in applet window. public void paint(Graphics g) { g.drawString("This is in the applet window.", 10, 20); showStatus("This is shown in the status window."); } } Sample output from this program is shown her  The HTML APPLET Tag  the APPLET tag can be used to start an applet from both an HTML document and from an applet viewer.  An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers will allow many applets on a single page.  Bracketed items are optional. < APPLET [CODEBASE = codebaseURL]

Passing Parameters to Applets  the APPLET tag in HTML allows to pass parameters to applet.  To retrieve a parameter, getParameter( ) method is used.  It returns the value of the specified parameter in the form of a String object.  Thus, for numeric and boolean values,its need to convert their string representations into their internal formats.  Here is an example that demonstrates passing parameters: // Use Parameters import java.awt.; import java.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(); } 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); }  conversions to numeric types must be attempted in a try statement that catches NumberFormatException. Uncaught exceptions should never occur within an applet. Improving the Banner Applet  It is possible to use a parameter to enhance the banner applet  However, passing the message as a parameter allows the banner applet to display a different message each time it is executed.  the APPLET tag specifies a parameter called message that is linked to a quoted string. // A parameterized banner import java.awt.; import java.applet.; /* */ public class ParamBanner extends Applet implements Runnable

// Pause the banner. public void stop() { stopFlag = true; t = null; } // Display the banner. public void paint(Graphics g) { g.drawString(msg, 50, 30); } }  getDocumentBase( ) and getCodeBase( )  Java allows applet to load data from the directory holding the HTML file that started the applet (the document base)  and the directory from which the applet’s class file was loaded (the code base).  These directories are returned as URL objects by getDocumentBase( ) and getCodeBase( ).  To actually load another file, will use the showDocument( ) method defined by the AppletContext interface. import java.awt.; import java.applet.; import java.net.; / */ public class Bases extends Applet { // Display code and document bases. public void paint(Graphics g) { String msg; URL url = getCodeBase(); // get code base msg = "Code base: " + url.toString(); g.drawString(msg, 10, 20); url = getDocumentBase(); // get document base msg = "Document base: " + url.toString(); g.drawString(msg, 10, 40); }

Sample output from this program is shown here: AppletContext and showDocument( )  One application of Java is to use active images and animation to provide a graphical means of navigating the Web that is more interesting than simple text-based links.  To allow applet to transfer control to another URL, we use showDocument( ) method defined by the AppletContext interfac  The context of the currently executing applet is obtained by a call to the getAppletContext( ) method defined by Applet.  This method has no return value and throws no exception if it fails.  There are two showDocument( ) methods.  The method showDocument(URL) displays the document at the specified URL.  The method showDocument(URL, String) displays the specified document at the specified location within the browser window.  The methods defined by AppletContext are shown in Method Description Applet getApplet(String appletName) Returns the applet specified by appletName if it is within the current applet context. Otherwise, null is returned. Enumeration getApplets( ) Returns an enumeration that contains all of the applets within the current applet context. AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. Image getImage(URL url) Returns an Image object that encapsulates the image found at the location specified by url. InputStream getStream(String key) Returns the stream linked to key. Keys are linked to streams by using the setStream( ) method. A null reference is returned if no stream is linked to key.

The AudioClip Interface  The AudioClip interface defines these methods: play( ) (play a clip from the beginning), stop( ) (stop playing the clip), and loop( ) (play the loop continuously).  After its loaded ,using getAudioClip( ), we can use these methods to play it. The AppletStub Interface  The AppletStub interface provides the means by which an applet and the browser (or applet viewer) communicate. Outputting to the Console  Although output to an applet’s window must be accomplished through GUI-based methods, such as drawString( ), it is still possible to use console output  In an applet,if System.out.println( ), the output is not sent to applet’s window.  Instead, it appears in the Java console that is available in some browsers.  Use of console output for purposes other than debugging is discouraged, since it violates the design principles of the graphical interface most users will expect.

JAVA AND J2EE NOTES

1

Unit --- 3

Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables. Even familiar components such as buttons have more capabilities in Swing. For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes. Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and, therefore, are platform-independent. The term lightweight is used to describe such elements. Swing are built on AWT. Explain two key features of Swing.

  1. Swing components are light weight They are entirely written in java they does not map to native platform specific code. More flexible and more efficient. Not in rectangular shapes.
  2. Swing supports a pluggable look and feel. It becomes possible to change the that component is rendered with out affecting any of its other aspects. Possible to create new look and feel for any given component with out side effects. Look and feel is simply plugged in. Briefly explain Container and Component of Swing.
  3. A Swing GUI consists of two key items: Components and Container
  4. A term component is an independent visual control such as push button or slider.
  5. A container holds group of components. Thus container is special kind of component that holds that is designed to hold other components. Container are also called components so container can hold other container.

Components

  1. Swing components are derived from JComponent Class. Supports pluggable look and feel. It inherits Component and Container of AWT.