COMP 519: Web Programming Autumn 2014 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling.

Slides:



Advertisements
Similar presentations
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Advertisements

1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Java Applets. An applet is a Panel that allows interaction with a Java program. A applet is typically embedded in a Web page and can be run from a browser.
Java Applet & JavaScript SNU OOPSLA Lab. October 2005.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
18-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
COMP 519: Web Programming Fall 2006 Acknowledgment: The slides are by Dr. David Reed.Dr. David Reed Java Overview  Design goals & features  platform.
Chapter 14 Applets. 2 Knowledge Goals Understand the differing roles of applications and applets Understand how a browser operates Understand the role.
Applets. An applet is a Panel that allows interaction with a Java program A applet is typically embedded in a Web page and can be run from a browser You.
26-Jun-15 Applets. 2 An applet is a Panel that allows interaction with a Java program A applet is typically embedded in a Web page and can be run from.
28-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
Applets. What is an Applet?  According to Sun “An applet is a small program that is intended not to be run on its own, but rather to be embedded inside.
PHY281Introduction to JavaSlide 1 Introduction to Java In this section we will learn how how to use Java and write our first Java Applet:  The Java Development.
Introduction to JavaScript. Aim To enable you to write you first JavaScript.
1 CSC 551: Web Programming Spring 2004 Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, … 
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, …  Programming models  applications vs. applets.
CS413: Java Programming language Applications Applets
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
1 CSC 551: Web Programming Spring 2004 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling.
CSC 551: Web Programming Fall 2001 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
Java Programming, 3e Concepts and Techniques Chapter 2 - Part 2 Creating a Java Application and Applet.
Slides © Marty Hall, book © Sun Microsystems Press 1 Including Files & Applets in JSP Documents Core Servlets & JSP book:
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JAVA APPLETS By: Ms. Humaira Siddiqui. Java and the Internet Java is considered to be a language well suited to be used in the internet. In contrast with.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
Chapter 34 Java Technology for Active Web Documents methods used to provide continuous Web updates to browser – Server push – Active documents.
OOP (Java): Simple/ OOP (Java) Objectives – –give some simple examples of Java applications and one applet 2. Simple Java Programs Semester.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
CS 3131 Introduction to Programming in Java Rich Maclin Computer Science Department.
Active Server Pages  In this chapter, you will learn:  How browsers and servers interacted on the Internet when the Internet first became popular 
Java Applets. An applet is a Panel that allows interaction with a Java program. A applet is typically embedded in a Web page and can be run from a browser.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Java Applets. 2 Introduction to Java Applet Programs Applications are ___________________ programs –executed with Java interpreter Applet is a small program.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Pravin Yannawar, DOCS, NMU Jalgaon Basic Java : Applets 2 Objectives of This Session Identify the need for Applets Distinguish between Applets and Applications.
Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language) document containing.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Applets Yong Choi School of Business CSU, Bakersfield.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
Chapter 14 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
1 Applets are small applications that are accessed on an Internet server, transported over the internet, automatically installed and run as a part of web.
Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, …  Programming models  applications vs. applets.
Creating a Java Application and Applet
1 Applets. 2 What is an applet? Applet: a Java program that can be inserted into a web page and run by loading that page in a browser brings web pages.
CHAPTER Agenda Applets Servelets Browsers HelloWorld.
COMP 519: Web Programming Autumn 2010 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
1 Applets Programming. Introduction Java programs are divided into two main categories, applets and applications. An application is an ordinary Java program.
Web Programming Java Script-Introduction. What is Javascript? JavaScript is a scripting language using for the Web. JavaScript is a programming language.
1 CSC 551: Web Programming Spring 2004 Java Applets  Java vs. C++  instance vs. class variables, primitive vs. reference types, inheritance  graphical.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Applet Programming Barry Sosinsky Valda Hilley
UNIT-5.
Java Applets.
CSC 551: Web Programming Spring 2004
CSC 551: Web Programming Spring 2004
JAVA APPLET PREPARED BY Mr. Jahanzaib Ahmed
Presentation transcript:

COMP 519: Web Programming Autumn 2014 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling an applet from JavaScript  accessing JavaScript & HTML elements from an applet  related topics  Java archives (JARs), JavaBeans

recall: JavaScript is very good for simple tasks, simple GUI layout can be handled by CSS  flexible data typing, primitive object types are fine for quick development  integration with HTML makes layout & control of GUI elements via DOM manipulation possible  only primitive data structuring capabilities  not well-suited to multi-file projects and complex OO approach JavaScript vs. Java Java is better at complex tasks, especially graphics  full-featured, more robust, extensive libraries of classes/routines  can support large projects, interacting objects  GUI layout in a webpage is difficult, integration with HTML not obvious IDEALLY: we can make use of the the strengths of each language  include applets in a page when needed (e.g., graphics)  allow communication between applet & JavaScript code

Calling Java Routines from JavaScript On some previous versions of web browsers, you used to be able to call (some) Java methods directly inside a JavaScript block. There were additional limitations, such as not being able to call Java functions to read and write from the local hard drive (for obvious security issues). This functionality seems to have largely disappeared from modern versions of web browsers. There is some additional technology, such as the Java Server Pages, which can give web programmers more of the expressive and computational power of Java. However, this requires a web server with a compatible "servelet container" for this to work (we don't have that technology installed on the web servers here).

Calling Applet Methods These days, we generally include a more complicated applet in a page to perform some task, and control the applet via HTML events, event handlers, and JavaScript. This requires a Java virtual machine (or Java runtime environment) to be installed on the client's machine, i.e. one that can execute Java bytecode. To call a Java applet method from JavaScript document.appletName.methodCall(…) What follows is a simple “Hello World” applet.

Java source code: import java.awt.*; import java.applet.*; /** * This class displays "Hello world!" on the applet window. */ public class HelloWorld extends Applet { public void paint(Graphics g) { // writes starting at pixel row 15, col 15 g.drawString("Hello world!", 15, 15); } Compile this source code as normal into a Java class. “Hello World” Java applet

Hello World Page table { border: 3px double; margin-left: auto; margin-right: auto; } <object codetype="application/java" codebase=" classid="java:HelloWorld.class" name="HelloApplet" height="30" width="100"> You must use a Java-enabled browser to view this applet. “Hello World” Java applet (cont.) view page

As one might expect, this may not really work on all browsers, due to the way different browsers have implemented the element. There are pure HTML methods you can use that (are supposed to) work for different browsers, or you can use JavaScript to detect different browsers and write appropriate HTML code depending upon the browser. The previous example actually contains more code than was shown, as I used some JavaScript to detect the type of browser, and use (I hope) suitable HTML code that would work to load the applet. (Of course, this also relies upon the user allowing JavaScript to run in his/her browser.) You might also have to deal with "deploying" your applet in a way to deal with security issues. (Most browsers give warnings for "unsigned" applets.) Browser differences...

One could replace the element in the previous HTML code with the following JavaScript code: // ***** <![CDATA[ var _app = navigator.appName; if (_app == 'Microsoft Internet Explorer') // ** Handle Internet Explorer { document.write('<object classid="clsid:8AD9C E-11D1-B3E F499D93" ', 'codetype="application/java" ', 'codebase=" ', 'name="HelloApplet" height="20" width="100"> ', ' ', 'You must use a Java-enabled browser to view this applet. ', ' '); } else // ** Handle all other browsers (I hope! Haven’t tested it on all!!) { document.write('<object codetype="application/java" ' 'codebase=" ', 'classid="java:HelloWorld.class" ', 'name="HelloApplet" height="20" width="100"> ', 'You must use a Java-enabled browser to view this applet. ', ' '); } // ***** ]]> Browser differences... (cont.)

In the examples that follow, I will include JavaScript code like the previous case in the HTML source code, but (for purposes of simplification) won’t include all of that in the example code shown. I will only show the syntax that works for (all?) browsers other than Internet Explorer, but it’s easy to replicate the JavaScript code for the previous example. Browser differences... (cont.)

Suppose we return to the example on permutations...  We had a JavaScript method to perform this task.  Let’s replace that method with a Java applet.  We can reuse much of the HTML code and need to supply Java code to perform the operation for us.  We continue using JavaScript methods to access the input (and output) fields on the HTML page, only using Java for the actual “calculation”. Permutations (again)

import java.awt.*; import java.applet.*; import java.util.Random; import java.lang.Math.*; /** * This class can be used to generate a permutation to be * inserted into a webpage. */ public class JavaPermutation extends Applet { public String permutation(int n) { Random r = new Random(); int[] p = new int[n]; int i, k, temp; for (i = 0; i < n ; i++) p[i] = i+1; double finish = Math.pow(n,3) * Math.log(n) * 12; for (i = 1; i <= finish; i++) { if (r.nextDouble() < 0.5) { k = r.nextInt(p.length - 1); temp = p[k]; p[k] = p[k + 1]; p[k+1] = temp; } Permutations (cont.)

String message = ""; for (i = 0; i < n; i++) message = message + p[i] + " "; return message; } public void paint(Graphics g) { // ** There’s no code here as we don’t want the application to write // anything to the screen itself. } } //** end of Java code We compile this code as normal to make a Java class. As stated, we can reuse much of the HTML code, we just need to add the part to insert the applet in the document and call the Java function (and we can remove the non-used JavaScript code). Permutations (cont.)

Generating random permutations p { text-align: center; } <!-- Script for verifying that a textbox contains an integer in a specified range. --> // <![CDATA[ function checkForEnter(Box, event) { if ( (event.keyCode == 13) && (Box.value != "") ) { return true; } return false; } function Process() { var n = document.getElementById('N'); if (VerifyIntInRange(n, 1, 50)) { var perm = document.PermApplet.permutation(parseInt(n.value)); var out = document.getElementById('Output'); out.value = perm; } n.focus(); } // ]]> Permutations (cont.)

<object codetype="application/java" codebase=" classid="java:JavaPermutation.class“ name="PermApplet" height="1" width="1"> You must use a Java-enabled browser to view this applet. Here is a function that will generate random permutations of a set of integers, where a permutation is just an arrangement of the integers {1, 2,..., n}. Enter a positive integer n (1-50): <input type="text" id="N" size="1" maxlength="2" value="15" onkeyup="if (checkForEnter(this, event)) { Process(); } " /> <input type="button" value="Go!" onclick="Process();" /> Random permutation of {1,..., n}. Permutations (cont.) view page

A (much?) more complicated example Consider MontePI example:  want to draw random dots inside a square (with an inscribed circle)  could build GUI interface into applet, but requires tricky layout manager  instead, leave graphics up to the applet, control the operation of the applet via JavaScript

MontePI import java.awt.*; import java.applet.*; import java.util.Random; public class Monte6 extends Applet { private static Random randy; private int SIZE; private Image offScreenImage; private Graphics offScreenGraphics; private int randomInRange(int low, int high) {…} private double distance(int x1, int y1, int x2, int y2) {…} public void init() { randy = new Random(); Dimension dim = getSize(); SIZE = dim.width; drawCircle(); } public void drawCircle() { // DRAWS CIRCLE ON BOTH getGraphics() AND // offScreenGraphics } public void drawDots(int numPoints) { // DRAWS numPoints RANDOM DOTS ON BOTH getGraphics() // AND offScreenGraphics } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } init creates the random number generator & gets applet size drawDots draws the dots on the screen and to the off-screen buffer paint redraws the screen using the buffer

MontePI (cont.) Monte Carlo Darts Page body { background-color: gray; } <object codetype="application/java" codebase=" classid="java:Monte6.class" name="MonteApplet" height="300" width="300"> You must use a Java-enabled browser to view this applet. <input type="button" value="Generate points" onclick="document.MonteApplet.drawDots(500);" /> As before, HTML button controls the applet (via JavaScript). view page

Example (cont.) Monte Carlo Darts Page body { background-color: gray; } <object codetype="application/java" codebase=" va/" classid="java:Monte6.class" name="MonteApplet" height="300" width="300"> You must use a Java-enabled browser to view this applet. <input type="button" value="Generate" onclick="numDots = parseFloat(getElementById('numPoints').value); document.MonteApplet.drawDots(numDots);" /> points <input type="button" value="Clear the screen" onclick="document.MonteApplet.drawCircle();" /> better interface: allow user to specify number of dots in text box each click adds new dots, have separate button to clear view page

Dividing Control where the control lies affects the efficiency/usability of an applet  want the applet to be as self-contained as possible, take advantage of speed of Java, more advanced features  but if GUI controls are in HTML, then JavaScript needs overall control consider adding counters for number of dots inside & outside circle  have the applet keep track of the dots in instance variables 1.call method to draw all dots, then JavaScript accesses counts & display  fast, but only see counts when done 2.could return more control to the page, applet draws one dot at a time  repetition is handled by JavaScript, can update boxes after each dot  slower, but more flexible (and can see counts change) 3.could have applet update the HTML text boxes itself  tricky, ties the applet to the page

JavaScript in Control import java.awt.*; import java.applet.*; import java.util.Random; public class Monte7 extends Applet {... public int numInside, numOutside; public void drawCircle() { numInside = 0; numOutside = 0;... } public void drawDots(int numDots) {... for (int i = 0; i < numPoints; i++) { int x = randomInRange(0, SIZE); int y = randomInRange(0, SIZE); if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) { offScreenGraphics.setColor(Color.white); g.setColor(Color.white); numInside++; } else { offScreenGraphics.setColor(Color.black); g.setColor(Color.black); numOutside++; }... }... } have applet keep track of number inside & out instance variables numInside and numOutside are initialized in drawCircle, updated in drawDots since they are public, these instance variables can be accessed in the webpage

Example (cont.) Monte Carlo Darts Page table { margin-left: auto; margin-right: auto; } body { background-color: gray; } function drawAll() { var numDots = parseFloat(document.forms['MonteForm'].numPoints.value); document.MonteApplet.drawDots(numDots); document.forms['MonteForm'].numIn.value = document.MonteApplet.numInside; document.forms['MonteForm'].numOut.value = document.MonteApplet.numOutside; document.forms['MonteForm'].estPi.value = 4.0*document.MonteApplet.numInside / (document.MonteApplet.numInside + document.MonteApplet.numOutside); } function clearAll() { document.MonteApplet.drawCircle(); document.forms['MonteForm'].numIn.value = 0; document.forms['MonteForm'].numOut.value = 0; } <object codetype="application/java" codebase=" classid="java:Monte7.class" name="MonteApplet" height="300" width="300"> You must use a Java-enabled browser to view this applet. points points inside points outside /tr> Note: can utilize HTML table to achieve desired layout of elements view page

Example (cont.) Monte Carlo Darts Page function drawAll() { var numDots = parseFloat(document.forms['MonteForm'].numPoints.value); for (var i = 0; i < numDots; i++) { document.MonteApplet.drawDots(1); document.forms[‘MonteForm’].numIn.value = document.MonteApplet.numInside; document.forms[‘MonteForm’].numOut.value = document.MonteApplet.numOutside; document.forms['MonteForm'].estPi.value = 4.0*document.MonteApplet.numInside / (document.MonteApplet.numInside + document.MonteApplet.numOutside); } } function clearAll() { document.MonteApplet.drawCircle(); document.forms['MonteForm'].numIn.value = 0; document.forms['MonteForm'].numOut.value = 0; } <td <object codetype="application/java" codebase=" classid="java:Monte7.class" name="MonteApplet" height="300" width="300">You must use a Java-enabled browser to view this applet. points points inside points outside Alternatively: could draw each dot individually, display counts after each dot view page

Accessing HTML/JavaScript from the Applet it is possible for the applet to access elements in the page  requires the JSObject class from the netscape.javascript package import netscape.javascript.JSObject;  use getWindow and getMember methods to access components JSObject jsWin = JSObject.getWindow(this); // GETS WINDOW JSObject jsDoc = (JSObject) jsWin.getMember("document"); // GETS DOCUMENT JSObject MonteForm = (JSObject) jsDoc.eval("document.forms[0]"); // GETS FORM numInside = (JSObject) MonteForm.getMember("numIn"); // GETS TEXT BOX  use getMember and setMember methods to access component attributes int num = Integer.parseInt( (String)numInside.getMember("value") ); numInside.setMember("value", ""+(num+1));

Java in Control import java.awt.*; import java.applet.*; import java.util.Random; import netscape.javascript.JSObject; // need plugin.jar in classpath public class Monte8 extends Applet {... private JSObject numDots, numInside, numOutside; public void init() {... try { JSObject jsWin = JSObject.getWindow(this); JSObject jsDoc = (JSObject) jsWin.getMember("document"); JSObject MonteForm = (JSObject) jsDoc.eval("document.forms[0]"); numDots = (JSObject) MonteForm.getMember("numDots"); numInside = (JSObject) MonteForm.getMember("numIn"); numOutside = (JSObject) MonteForm.getMember("numOut"); } catch (netscape.javascript.JSException jse) { } drawCircle(); } public void drawDot() {... int inCount = 0; outCount = 0; if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {... inCount++; } else {... outCount++; } int newIn = Integer.parseInt((String)numInside.getMember("value"))+ inCount; numInside.setMember("value", ""+newIn); int newOut = Integer.parseInt((String)numOutside.getMember("value"))+ outCount; numOutside.setMember("value", ""+newOut); } public void drawCircle() { numInside.setMember("value", "0"); numOutside.setMember("value", "0");... }

Example (cont.) Monte Carlo Darts Page table { margin-left: auto; margin-right: auto; } body { background-color: gray; } <object codetype="application/java" codebase=" classid="java:Monte8a.class" name="MonteApplet" height="300" width="300"> You must use a Java-enabled browser to view this applet. <input type="button" value="Generate" onclick="document.MonteApplet.drawDots();" /> points points inside points outside <input type="button" value="Clear the screen" onclick="document.MonteApplet.drawCircle();" /> mayscript attribute must be specified in a param tag to allow the Java program to access HTML elements & JavaScript in the page view page

Related Topics JavaBeans  reusable components (e.g., buttons, menus) that can be packaged and reused  requires special tools for compiling and packaging (e.g., BDK) JAR files  for applets that are comprised of multiple classes, can bundle all necessary files into a Java Archive (JAR) file  uses the popular ZIP file format  download using ARCHIVES attribute, automatically unzipped by browser