Download presentation
Presentation is loading. Please wait.
Published byPhyllis Stone Modified over 9 years ago
1
24.1Introduction Java Powerful, object-oriented language Fun to use for beginners, appropriate for experience programmers Language of choice for Internet and network communications In the Java chapters, we discuss Graphics (and graphical user interfaces [GUI] ) Multimedia Event-driven programming Free implementation at http://java.sun.com
2
24.2Basics of a Typical Java Environment Java Systems Consist of environment, language, Java Applications Programming Interface (API), Class libraries Java programs have five phases Edit Use an editor to type Java program vi or emacs, notepad, Jbuilder, Visual J++.java extension Compile Translates program into bytecodes, understood by Java interpreter javac command: javac myProgram.java Creates.class file, containing bytecodes ( myProgram.class )
3
24.2Basics of a Typical Java Environment (II) Java programs have five phases (continued) Loading Class loader transfers.class file into memory Applications - run on user's machine Applets - loaded into Web browser, temporary Classes loaded and executed by interpreter with java command java Welcome HTML documents can refer to Java Applets, which are loaded into web browsers. To load, appletviewer Welcome.html appletviewer is a minimal browser, can only interpret applets
4
24.2Basics of a Typical Java Environment (II) Java programs have five phases (continued) Verify Bytecode verifier makes sure bytecodes are valid and do not violate security Java must be secure - Java programs transferred over networks, possible to damage files (viruses) Execute Computer (controlled by CPU) interprets program one bytecode at a time Performs actions specified in program Program may not work on first try Make changes in edit phase and repeat
5
Program is created in the editor and stored on disk. Compiler creates bytecodes and stores them on disk. Class loader puts bytecodes in memory. Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. Phase 1 Phase 2 Phase 3 Phase 4 Phase 5 Disk Edito r Compile r Class Loader Disk Primary Memory............ Primary Memory............ Primary Memory............ Bytecode Verifier Interpret er
6
24.3General Notes about Java and This Book Java Powerful language Programming Clarity - Keep it Simple Portability - Java portable, but it is an elusive goal Some details of Java not covered http://java.sun.com for documentation Performance Interpreted programs run slower than compiled ones Compiling has delayed execution, interpreting executes immediately Can compile Java programs into machine code Runs faster, comparable to C / C++
7
24.3General Notes about Java and This Book (II) Just-in-time compiler Midway between compiling and interpreting As interpreter runs, compiles code and executes it Not as efficient as full compilers Being developed for Java Integrated Development Environment (IDE) Tools to support software development Several Java IDE's are as powerful as C / C++ IDE's
8
24.4A Simple Program: Printing a Line of Text Application Program that runs using Java interpreter (discussed later) Comments Java uses C-style // (preferred by Java programmers) Can also use /*... */ 1// Fig. 24.2: Welcome1.java 2// A first program in Java 3 4public class Welcome1 { 5 public static void main( String args[] ) 6 { 7 System.out.println( "Welcome to Java Programming!" ); 8 } 9}9}
9
24.4A Simple Program: Printing a Line of Text (II) public class Welcome1 { Begins class definition Every Java program has a user-defined class Use keyword (reserved word) class followed by ClassName Name format - MyClassName Identifier - letters, digits, underscores, dollar signs, does not begin with a digit, contains no spaces Java case sensitive public - For Chapters 24 and 25, every class will be public Later, discuss classes that are not (Chapter 26) Programmers initially learn by mimicking features. Explanations come later. When saving a file, class name must be part of file name Save file as Welcome1.java
10
24.4A Simple Program: Printing a Line of Text (III) Braces Body - delineated by left and right braces Class definitions public static void main( String args[] ) Part of every Java application Program begins executing at main Must be defined in every Java application main is a method (a function) void means method returns nothing Many methods can return information Braces used for method body For now, mimic main 's first line
11
24.4A Simple Program: Printing a Line of Text (IV) System.out.println( "Welcome to Java Programming!" ); Prints string String - called character string, message string, string literal Characters between quotes a generic string System.out - standard output object Displays information in command window Method System.out.println Prints a line of text in command window When finished, positions cursor on next line Method System.out.print As above, except cursor stays on line \n - newline Statements must end with ;
12
24.4A Simple Program: Printing a Line of Text (V) Executing the program javac Welcome1 Creates Welcome1.class (containing bytecodes) java Welcome1 Interprets bytecodes in Welcome1.class (.class left out in java command) Automatically calls main Output types Command window Dialog box / Windows
13
24.4A Simple Program: Printing a Line of Text (VI) Packages Predefined, related classes grouped by directories on disk All in directory java or javax, or subdirectories Referred to collectively as the Java class library or the Java applications programming interface (Java API) import - locates classes needed to compile program Class JOptionPane Defined in package called javax.swing Contains classes used for a graphical user interface (GUI) Facilitates data entry and data output import javax.swing.JOptionPane;
14
24.4A Simple Program: Printing a Line of Text (VII) Class JOptionPane Contains methods that display a dialog box static method showMessageDialog First argument - null (more Chapter 29) Second argument - string to display static methods Called using dot operator (. ) then method name JOptionPane.showMessageDialog(arguments); exit - method of class System Terminates application, required in programs with GUIs System.exit( 0 ); 0 - normal exit non-zero - signals that error occurred Class System in package java.lang Automatically imported in every Java program
15
15 Applets Programming Enabling Application Delivery Via the Web
16
16 Introduction Applets are small Java programs that are embedded in Web pages. They can be transported over the Internet from one computer (web server) to another (client computers). They transform web into rich media and support the delivery of applications via the Internet.
17
Introduction to Applets Applets are applications that are deployed over the Internet Designed to run inside a browser Are embedded in HTML pages Core part of Java Not are popular as they were (or forecasted to be) Patchy browser support Can be slow to download Macromedia Flash, etc. offer similar functionality
18
Introduction to Applets But do provides a number of benefits… Easy to deploy (“web components”) No need for installation or upgrades Provide more sophisticated functionality than a web page/form Allow for proprietary client-server protocols Re-use code from traditional applications Very secure
19
The Rules for Applets An applet cannot (usually) do the following: Cannot load libraries or define native methods Cannot read or write files on the client Cannot make network connections except to the server it came from Cannot start any program on the client Cannot read certain system properties Cannot ‘pretend’ to be a local application Applet windows look different
20
The Rules for Applets Ensures that an applet cannot damage the client Otherwise opens potential for viruses, security breaches, trojan horses, etc Applets are considered to be untrusted code Rules are enforced by a Security Manager Installed by the JVM in the browser The rules are known as a security policy Alternate policies can be used on request But only if the user decides to trust the code
21
21 Applet: Making Web Interactive and Application Delivery Media Hello Hello Java <app= “Hello”> 4 APPLET Development “hello.java” AT SUN.COM The Internet hello.class AT SUN’S WEB SERVER 2 31 5 Create Applet tag in HTML document Accessing from Your Organisation The browser creates a new window and a new thread and then runs the code
22
22 How Applets Differ from Applications Although both the Applets and stand-alone applications are Java programs, there are certain restrictions are imposed on Applets due to security concerns: Applets don’t use the main() method, but when they are load, automatically call certain methods (init, start, paint, stop, destroy). They are embedded inside a web page and executed in browsers. They cannot read from or write to the files on local computer. They cannot communicate with other servers on the network. They cannot run any programs from the local computer. They are restricted from using libraries from other languages. The above restrictions ensures that an Applet cannot do any damage to the local system.
23
23 Building Applet Code: An Example //HelloWorldApplet.java import java.applet.Applet; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString ("Hello World of Java!",25, 25); }
24
24 Embedding Applet in Web Page Hello World Applet Hi, This is My First Java Applet on the Web!
25
25 Accessing Web page (runs Applet)
26
26 Applet Life Cycle Every applet inherits a set of default behaviours from the Applet class. As a result, when an applet is loaded, it undergoes a series of changes in its state. The applet states include: Initialisation – invokes init() Running – invokes start() Display – invokes paint() Idle – invokes stop() Dead/Destroyed State – invokes destroy()
27
27 Applet States Initialisation – invokes init() – only once Invoked when applet is first loaded. Running – invokes start() – more than once For the first time, it is called automatically by the system after init() method execution. It is also invoked when applet moves from idle/stop() state to active state. For example, when we return back to the Web page after temporary visiting other pages. Display – invokes paint() - more than once It happens immediately after the applet enters into the running state. It is responsible for displaying output. Idle – invokes stop() - more than once It is invoked when the applet is stopped from running. For example, it occurs when we leave a web page. Dead/Destroyed State – invokes destroy() - only once This occurs automatically by invoking destroy() method when we quite the browser.
28
28 Applet Life Cycle Diagram Born RunningIdle Dead Begin init() start() paint() stop() start() destroy() End
29
29 Passing Parameters to Applet Hello World Applet Hi, This is My First Communicating Applet on the Web! <APPLET CODE="HelloAppletMsg.class" width=500 height=400>
30
30 Applet Program Accepting Parameters //HelloAppletMsg.java import java.applet.Applet; import java.awt.*; public class HelloAppletMsg extends Applet { String msg; public void init() { msg = getParameter("Greetings"); if( msg == null) msg = "Hello"; } public void paint(Graphics g) { g.drawString (msg,10, 100); } This is name of parameter specified in PARAM tag; This method returns the value of paramter.
31
31 HelloAppletMsg.html
32
32 What happen if we don’t pass parameter? See HelloAppletMsg1.html Hello World Applet Hi, This is My First Communicating Applet on the Web! <APPLET CODE="HelloAppletMsg.class" width=500 height=400>
33
33 getParameter() returns null. Some default value may be used.
34
34 Displaying Numeric Values //SumNums.java import java.applet.Applet; import java.awt.*; public class SumNums extends Applet { public void paint(Graphics g) { int num1 = 10; int num2 = 20; int sum = num1 + num2; String str = "Sum: "+String.valueOf(sum); g.drawString (str,100, 125); }
35
35 SunNums.html Hello World Applet Sum of Numbers
36
36 Applet – Sum Numbers
37
37 Interactive Applets Applets work in a graphical environment. Therefore, applets treats inputs as text strings. We need to create an area on the screen in which use can type and edit input items. We can do this using TextField class of the applet package. When data is entered, an event is generated. This can be used to refresh the applet output based on input values.
38
38 Interactive Applet Program..(cont) //SumNumsInteractive..java import java.applet.Applet; import java.awt.*; public class SumNumsInteractive extends Applet { TextField text1, text2; public void init() { text1 = new TextField(10); text2 = new TextField(10); text1.setText("0"); text2.setText("0"); add(text1); add(text2); } public void paint(Graphics g) { int num1 = 0; int num2 = 0; int sum; String s1, s2, s3; g.drawString("Input a number in each box ", 10, 50); try { s1 = text1.getText(); num1 = Integer.parseInt(s1); s2 = text2.getText(); num2 = Integer.parseInt(s2); } catch(Exception e1) {}
39
39 Interactive Applet Program. sum = num1 + num2; String str = "THE SUM IS: "+String.valueOf(sum); g.drawString (str,100, 125); } public boolean action(Event ev, Object obj) { repaint(); return true; }
40
40 Interactive Applet Execution
41
41 Summary Applets are designed to operate in Internet and Web environment. They enable the delivery of applications via the Web. This is demonstrate by things that we learned in this lecture such as: How do applets differ from applications? Life cycles of applets How to design applets? How to execute applets? How to provide interactive inputs?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.