Java applets

2,613 views

Published on

Published in: Technology, Art & Photos
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,613
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
290
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Java applets

  1. 1. Java is a powerful, object-oriented language. Creating a Java application involves the following : Writing the application in Java Saving the application with a .java file extension Compiling the application into butecode using the javac command. The bytecode is then stored in a file with a .class file extension. Using the java command to interpret and execute the .class file.
  2. 2. Java is the language of choice for Internet and network communications. Java programs are divided into two main categories, applets and applications. Java Applets are making websites more and more sophisticated. Highly graphical techniques bring more interactivity and visual effects to your website.
  3. 3. An application is : an ordinary Java program a stand-alone program that execute beginning with their main () methods. An applet is : a small program or utility with limited features, requiring minimal resources usually designed to run within a larger program a java program that is called from within another application a kind of Java program that can be run across the Internet
  4. 4. A program written in the Java programming language Typically comes with an HTML (HyperText Markup Language) document and executed when the document is viewed. Appletviewer is a stand alone tool provided by the Java Software Development Kit (SDK) that is used to execute applets mainly for testing purposes.
  5. 5. HTML or HyperText Markup Language is a simple markup language . A markup language is a coding system used to structure a document by embedding sets of labels called tags within the text. HTML is used to create web pages for the Internet. HTML contains many commands that allow a programmer to format text on a Web page, import graphic images, and link a page to other Web pages. A web page linked to other Web pages is called a hyperlink
  6. 6. To create an applet in Jave : Write the applet in Java then save it with a .java file extension, just like when you do in a Java application Compile the applet into bytecode using javac command, just like you do when you write a Java application Write an HTML document that includes a statement to call your compiled Java class. Load the HTML document into a Web browser such as Google Chrome, Mozilla Firefox or MS Internet Explorer, or you can open the HTML document using the Applet Viewer provided by the Java SDK
  7. 7. HTML is made up of a collection of simple commands that can be inserted into a text file. This converts the text file into a document meant to be viewed with a Web browser Some commands allow pictures and hyperlinks to be inserted Others are editing commands that specify the main heading, subheading, paragraph beginning, and so forth
  8. 8. Much of HTML is simply a language for formatting text but it is not a word processor It is more like a very simple programming language It is similar to the annotations used by copy editors to mark a manuscript before it is typeset for production HTML is not part of the Java language There can be interaction between HTML and Java HTML can be used to display a Java applet program
  9. 9. There are two basic kinds of HTML commands : Those that mark the beginning and end of a section of text Those that mark a single location in the text The tag that begins every HTML document is <html>, which is surrounded by angle brackets. The html within the tag is an HTML keyword that specifies than an HTML document follows the keyword. The tag ends every HTML document is </htlm>. Inserting a backslash before any tag indicates that the tag is the ending half of a pair of tags
  10. 10. Example : A simple HTML document that does nothing in the process : Begins the HTML document <html> </html> Ends the HTML document This HTML document begins and ends, doing nothing in the process. This is similar to writing a Java method with an opening curly bracket followed immediately by a closing curly bracket.
  11. 11. Another pair of HTML tags that used in running applets from within an HTML document is the <object>-</object> tag pair Usually, three arguments are placed within the <object> tag. Code – name of the compiled applet you are calling. It should have a .class file extension and should be relative to the location of the HTML document. Width – width of the applet on the screen measured in pixels Height – height of the applet on the screen measured in pixels
  12. 12. Pixels are picture elements or tiny dots of light that make up an image on the video monitor. A width of 200 pixels and a height of 300 pixels, for example, will cover one fourth of the screen for monitors that display 800 pixels horizontally and 600 pixels vertically pixel
  13. 13. Example : Name of the applet you are calling Width of the applet on the screen in pixels <object code = “Aclass.class” width = 300 height = 200> </object> Height of the applet on the screen in pixels
  14. 14. Instead of <object> and </object> tag pair, you can use the tag pair <applet> and </applet> in your HTML applet host documents The WWW Consortium recommends using object rather than applet because it is more general and includes new and future media types, as well as applets.
  15. 15. Example : An HTML document that will run the applet named AnExample.class <html> <applet code = “AnExample.class” width = 400 Height = 200 > </applet> </html> The applet will be 400 pixels wide and 200 pixels tall. The AnExample.class file will reside in the same folder as the HTML file. Hence, there is no need to set the path in the object code argument.
  16. 16. Two ways to run an applet : Using a Web browser to open the associate HTML file Using the appletviewer
  17. 17. To run an applet using a Web browser : Select the File menu then click Open On the Open dialog box, type the complete path for the HTML document that you created or you may click on the Browse button to locate the file where you saved the HTML file. Press the Enter key. The applet appears on the web browser screen
  18. 18. To run an applet using the appletviewer : Type “appletviewer” at the command line followed by the full HTML filename, including the extension When you press the Enter key, the Applet Viewer window opens and displays the applet.
  19. 19. The appletviewer is used mainly for testing applets. The appletviewer is, in effect, a web browser that recognizes only the tags associated with the execution of an applet. All other HTML tags, as well as texts, are ignored. An appletviewer window will be opened for each applet loaded by the HTML file.
  20. 20. Include import statements to ensure that necessary classes are available Learn to use some user interface (UI) components, such as buttons and text fields, and applet methods Learn to use the keyword extends
  21. 21. Import statements such as javax.swing and java.awt.event are used to access classes within an application These classes are imported into your applications so you would not have to write them yourself. They have been prewritten because other programmers frequently need the same types of objects. In the same way, creators of java created an applet class named JApplet that you can import using the statement import javax.swing.Japplet JApplet is a Swing class from which you can instantiate an applet.
  22. 22. JApplet is the Swing equivalent of the AWT Applet class. JApplet is a simple extension of java.applet,Applet used when creating Swing programs designed to be used in a Web browser Like other JComponents, a JApplet can contain user interface (UI) components. As a direct subclass of Applet, JApplet is used in much the same way as the Applet.
  23. 23. The primary thing JApplet provides that Applet does not is the use of a JRoot Pane as its single display component A JApplet is a Component, and it is also a Container. In Java, every Applet, Container, and Component is also an Object. Object is a class to which all object belong.
  24. 24. Inheritance Hierarchy of the JApplet Class java.lang.Object java.awt.Component java.awt.Container java.awt.Panel java.applet.Applet Javax.swing.JApplet
  25. 25. The import statement below is needed when using the JApplet class : import javax.swing.*; You may also need the AWT library, so your list of import statements would look something like the one below : import javax.swing.*; import java.awt.*; import.awt.event.*;
  26. 26. JApplet class extends the capabilities of the Container, Component, and Object classes. Any JApplet created extends the capabilities of the JApplet class. When you create an application, you follow any needed import statements with a class header such as the one shown below: public class Myclass
  27. 27. Applets start the same way as applications, by the words extends JApplet must also be included. The extends keyword indicates that the applet builds on or inherits the traits of the JApplet class. Like a JFrame, a JApplet contains a content pane and can contain a menu bar. You can add content to an applet either by adding content to its content pane or by replacing the content pane with another component.
  28. 28. Applets do not need the setVisible ( ) method. Applets are embedded in HTML documents, and it is the HTML document that displays the applet An applet does not require a main ( ) method.
  29. 29. Example of a java Applet : import javaax.swing.*; import java.awt.*; public class HelloApplet extends JApplet { public void init () { Container contentPane = getContentPane (); content.Pane.setLayout (new FlowLayout (); JLabel label = new JLabel ("Hello world!"); contentPane.add(label); } } When this applet is executed, it will create a pane in the web browser and display the text “hello world!” in the pane.
  30. 30. There is no need to use the setTitle ( ) method in an applet because applets do not have titles. Applets normally go into HTML documents. You can insert the title in the HTML document that displays the applet.
  31. 31. Four methods are called by a Web browser when it runs an applet public void init ( ) public void start ( ) public void stop ( ) public destroy ( ) You can create an applet using only the init () method. You must code the init () method‟s header as public void init ()
  32. 32. Java creates these methods for you if you fail to write one or more of these methods The methods Java creates are empty. They only have opening and closing braces. You must code statements within at least one of these methods to make your application do anything useful. The init () method is the first method called in any applet. The init () method is used to perform initialization tasks, such as setting variables to initial values or placing applet components on the screen
  33. 33. You can add components to your JApplet. In the previous example : We created a JLabel named label that held the words “Hello World!” We added the label object to an applet within its init () method using the add () method.
  34. 34. Swing Container must use a content pane to which components can be added A Container content pane object is created using the getContentPane ( ) method. We added the label object to the content pane with the statement : getContentPane( ) .add (label) ;
  35. 35. You can include JTextFields and JButtons in a JApplet. Example : Provide a JTextField for a user to answer the question “How are you?” and assign an empty string with 10 characters. JTextField answer = newJTextField (10) Add the JTextField named answer to the Container using : getContentPane () . add(answer) ;
  36. 36. To create a JButton with the label “Press me”, we write : JButton press = new JButton(“Press me”) ; Add the JButton to the Container getContentPane( ) .add(press) ; You can use a layout manager to place multiple components at specified positions in a container so they do not overlap and obscure each other.
  37. 37. Sample program to show a Japplet where the 3 components, a JLabel, JTextField, and a JButton, have been added. import javax.swing.*; Import java.awt.*; public class JHello extends JApplet { Container contentPane = getContentPane ( ) ; JLabel question = new JLabel (“What „s your name?”) ; JTextField answer = new JTextField (10) ; JButton press = new JButton (“Press me”) ; public void init () { contentPane.add(question); contentPane.add(answer); contentPane.add(press); contentPane.setLayout (new FlowLayout () ) ; } }
  38. 38. Below is the output of the JHello, using a FlowLayout when run in an Applet Viewer.
  39. 39. Applets inherit a group of event handling methods from the Container class. To respond to user events within any applet you create : Prepare your applet to accept event messages Tell your applet to expect events to happen Tell your applet how to respond to the events.
  40. 40. To accept mouse events in an applet : Import the java.awt.event package into your program Add the phrase implements ActionListener to the class header.
  41. 41. Implementing ActionListener provides you with standard event method specifications that allow your applet to work with ActionEvents ActionEvents are the type of events that occur when a user clicks a button.
  42. 42. To expect ActionEvents to happen in an applet, the addActionListener( ) method is used If you declare a JButton named button and you want to perform an action when a user clicks button, button is the source of a message. The statement button.addActionListener(this) causes any ActionEvent message that comes from button to be sent to the current object.
  43. 43. The ActionListener interface contains the actionPerformed (ActionEvent e) method specification. When an applet has registered as a listener with a Component such as a JButton, and a user clicks the JButton, the actionPerformed() method executes. The actionPerformed() method contains a header and a body, like all methods. The header public void actionPerformed(ActionEvent e) is used where e is any name you choose for the Event , like the JButton click, that initiated the notification of the ActionListener (the JApplet). The body of the method contains any statements that you want to execute when the action occurs
  44. 44. The previous program has been modified to show the use of events . The statements appearing in red are the modifications : import javax.swing.*; import java.awt.event.* ; Import java.awt.*; public class JHello extends JApplet implements ActionListener { Container contentPane = getContentPane ( ) ; JLabel question = new JLabel (“What „s your name?”) ; JTextField answer = new JTextField (10) ; JButton press = new JButton (“Press me”) ; Program continue on the next slide
  45. 45. public void init () { contentPane.add(question); contentPane.add(answer); contentPane.add(press); contentPane.setLayout (new FlowLayout () ) ; press.addActionListener (this) ; } publicvoid actionPerformed (ActionEvent e) { String name = answer.getText() ; System.out.println(“You pressed the nutton, “ + name) ; } }
  46. 46. Below is the output of the JHello when the user enters “Juan” into the JTextField and clicks the JButton.
  47. 47. You may want to make changes as various events occur. You may want to add new components to the applet when the user clicks an applet button instead of using a System.out.println statement. One way of doing this is by creating a new JLabel that you can add to the applet with the add() method after the user enters a name.
  48. 48. The following modifications have been added to our previous program. The statements appearing in red are the modifications : import javax.swing.*; import java.awt.event.* ; Import java.awt.*; public class JHello extends JApplet implements ActionListener { JLabel question = new JLabel (“What „s your name?”) ; JTextField answer = new JTextField (10) ; JButton press = new JButton (“Press me”) ; JLabel lbl = new Jlabel (“”); Container contentPane = getContentPane ( ) ; Program continue on the next slide
  49. 49. public void init () { contentPane.add(question); contentPane.add(answer); contentPane.add(press); contentPane.setLayout (new FlowLayout () ) ; press.addActionListener (this) ; answer.addActionListener (this) ; } publicvoid actionPerformed (ActionEvent e) { String name = answer.getText() ; lbl.setText(“Hello, “ + name + “!!) ; contentPane.add(lbl) ; validate () ; } }
  50. 50. In the actionPerformed() method, the validate () method is invoked to ensure that the Components draw themselves on the screen. Below is the output of the program :
  51. 51. You can also remove components from an applet. To remove components, use the remove () method. Place the component‟s name within the parenthesis For example, if you want to remove the JButton components after pressing it, you write: remove (press) ;
  52. 52. A browser manages an applet life cycle if an applet is loaded in a web page by calling certain methods. There are four like cycle methods of an Applet class on which any applet is built : init ( ) - called to initialize an applet start ( ) - called after the initialization of the applet stop ( ) – automatically called whenever the user moves away from the page containing applets. destroy ( ) – only called when the browser shuts down normally.
  53. 53. init ( ) method This method executes when a Web page containing an Applet is loaded in a browser or run using the appletviewer We should write our own init ( ) method when we have any initialization tasks to perform like setting up user interface components.
  54. 54. start ( ) method This method executes after the init ( ) method and it executes again every time the applet becomes active after it has been inactive. When you write your own start ( ) method, you must include any actions you want your applet to take when a user revisits the Applet.
  55. 55. stop ( ) method This method is used when a user leaves a Web page. You override the existing empty stop ( ) method only if you want to take some action when an Applet is no longer visible Usually, we do not need to write our own stop ( ) method.
  56. 56. destroy ( ) method This method is called when the user closes the browser or Applet Viewer. This releases any resources the Applet might have allocated.
  57. 57. Every Applet has the same life cycle outline. When any applet executes, the init ( ) method runs, followed by the start ( ) method. init ( ) start ( ) If the user leaves the Applet‟s page, the stop ( ) method executes. When the user returns, the start ( ) method executes. The start ( ) and stop ( ) sequence might continue any number of times until the user closes the browser or Applet Viewer. which uses the destroy ( ) method. stop ( ) destroy ( ) stop ( )
  58. 58. The following program shows the use of the four methods : import java.awt.*; import javax.swing.*; import java.awt.event.* ; public class LifeCycleDemo extends JApplet implements ActionListener { JLabel messInit = new JLabel (“init”) ; JLabel messStart = new JLabel (“start”) ; JLabel messDisplay = new JLabel (“display”) ; JLabel messAction = new JLabel (“action”) ; JLabel messStop = new JLabel (“stop”) ; JLabel messDestroy = new JLabel (“destroy”) ; JButton press = new JButton (“OK”) ; Program continue on the next slide
  59. 59. Container con = getContentPane ( ) ; init countInit, countStart, countDisplay, countAction, countStop, countDestroy; public void init ( ) { con.setLayout (new FlowLayout ( ) ) ; con.add (messInit); con.add (messStart; con.add (messDisplay); con.add (messAction); con.add (messStop); con.add (messDestroy); con.add (press); press.addActionListener (this) ; display ( ) ; Program continue on the next slide
  60. 60. } public void start ( ) { ++countStart; display( ) ; ) public void display ( ) ( ++countDisplay; messInit.setText (“init “ + countInit) ; messStartsetText (“start “ + countStart) ; messDisplay.setText (“display “ + countDisplay) ; messAction.setText (“action “ + countAction) ; messStop.setText (“istop “ + countStop) ; messDestroy.setText (“idestroy “ + countDestroy) ; Program continue on the next slide
  61. 61. } public void stop ( ) { ++countStop; display( ) ; ) public void destroy ( ) ( ++countDestroy; display( ) ; ) public void actionPerformed (ActionEvent e) { Object source – e.getSource ( ); if (source = = press) ( Program continue on the next slide
  62. 62. ++countAction; display( ) ; ) ) ) When the applet begins, the init ( ) method is called and 1 is added to countInit. The init ( ) method calls display ( ) and 1 is added to countDisplay.
  63. 63. Immediately after the init ( ) method executes, the start ( ) method is executed, and 1 is added to countStart. The start ( ) method calls display ( ), so 1 more is added to countDisplay. The actionPerformed ( ) , stop ( ), and destroy ( ) methods have not been executed the first time you run the applet.
  64. 64. The figure below shows the output of the program when run for the first time :
  65. 65. The setLocation( ) method is used to place a component at a specific location within the applet window. Example 1 : To position a JLabel object named lbl at the upper-left corner of the applet window, we write : lbl.setLocation (0,0); Example 2 : If a window is 200 pixels by 100 pixels tall, you can place a JButton named press in the center of the window with the statement press.setLocation (100,50);
  66. 66. An applet window consists of a number of horizontal and vertical pixels on the screen. The pixel values in the HTML document you write are set to test the JApplet. Any component placed on the screen has a horizontal or xaxis position and a vertical or y-axis position on the Applet window. The upper left corner of any display is position 0,0. The first , or x-coordinate, value increases as you move from left to right across the window. The second, or y-coordinate, value increases as you move from top to bottom.
  67. 67. The following program shows the use of a setLocation ( ) method to change the location of a JLabel each time JButton is clicked: import javax.swing.*; import java.awt.event.* ; import java.awt.*; public class MoveJLabel extends JApplet implements ActionListener { Container con = getContentPane ( ) ; JLabel moveMsg = new JLabel (“STI Incorporated”) ; JButton press = new JButton (“Press here”) ; int xLoc = 20, yLoc = 20 ; Program continue on the next slide
  68. 68. public void init ( ) { con.setLayout (new FlowLayout ( ) ) ; con.add (moveMsg) ; con.add (press) ; press.addAction Listener (this) ; ) public void actionPerformed (ActionEvent e) { moveMsg.setLocation (xLoc+=10, yLoc+=10) ; } }
  69. 69. The figure below shows the output of the moveJLabel :
  70. 70. The setEnabled ( ) method is used to make a component unavailable and then make it available again. Example : A JButton can become dim and unresponsive when the programmer no loger wants you to have access to the JButton‟s functionality. The setEnabled ( ) takes an argument of true if you want to enable the component ,or false if you want to disable a component. By default, a Component is enabled when you create it.
  71. 71. The following is a modification of the previous program to demonstrated the use of the setEnabled ( ) method. The statements appearing in red will disable the JButton when the message has moved to a y-coordinate of 280. : import javax.swing.*; import java.awt.event.* ; import java.awt.*; public class MoveJLabel extends JApplet implements ActionListener { Container con = getContentPane ( ) ; JLabel moveMsg = new JLabel (“STI Incorporated”) ; JButton press = new JButton (“Press here”) ; int xLoc = 20, yLoc = 20 ; Program continue on the next slide
  72. 72. public void init ( ) { con.setLayout (new FlowLayout ( ) ) ; con.add (moveMsg) ; con.add (press) ; press.addAction Listener (this) ; ) public void actionPerformed (ActionEvent e) { moveMsg.setLocation (xLoc+=10, yLoc+=10) ; if (yLoc == 280) press.setEnabled (false) ; } }
  73. 73. The Applet class is an older applet class that was used to produce applets before the JApplet class came. The Applet class cannot produce applets with as many features as the JApplet class can produce. For very simple applets, it is easy to convert JApplet to an Applet.
  74. 74. When your applet does not work on a wide array of browsers, use the Applet class instead by simply : Deleting all the Js, replacing JApplet with Applet, JButton with Button, and so forth Adding the import statement import java.applet.*; Deleting the import statement , import javax.swing.* ;
  75. 75. Unlike a JApplet, an Applet has no content pane. Hence, the add ( ) method is used along with the applet itself. Whatever you would do to the content pane of a JApplet, you do directly to an Applet. Example : If the init ( ) method in a Japplet contains the line : getContentPane.add(label) ; Then in an Applet you would simply write this as : add(label);

×