1 CSC 551: Web Programming Spring 2004 Java Applets  Java vs. C++  instance vs. class variables, primitive vs. reference types, inheritance  graphical.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
Programming and Problem Solving With Java Copyright 1999, James M. Slack Applets What is an Applet? Applet Parameters Graphics in Applets Other Applet.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
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.
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.
1 Features of Java CS 3331 Fall Outline  Abstract class  Interface  Application --- animation applets.
Java Programs u 1 project file –with an extension of.mcp –contains information that CodeWarrior needs to run the program u >= 1 source files –have an extension.
1 CSC 551: Web Programming Spring 2004 Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, … 
OOP Languages: Java vs C++
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
CSTP WS00CS423 (cotter)1 Java Applets Objective: Learn how to develop Java programs that interact with users through a Web browser.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
Applets Java API.
Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, …  Programming models  applications vs. applets.
Programming Languages and Paradigms Object-Oriented Programming.
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.
Java Programming, 3e Concepts and Techniques Chapter 2 - Part 2 Creating a Java Application and Applet.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Java applet basics, loading & displaying images After this section, you should be able to : –Use the applet tag and applet parameters –Describe what a.
COMP 519: Web Programming Autumn 2014 Combining Java & JavaScript  integrating Java with JavaScript  calling Java routines from JavaScript  controlling.
Java On The Web Session 15. Memory Upload JAVA Applets Colors Fonts Drawing Methods Posting your Applet.
JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
9/21/99www.cs.vt.edu/wwtut/1 User Interface Programming In Java Part 1 – Introduction Marc Abrams Virginia Tech CS Dept courses.cs.vt.edu/wwwtut/
Java Applet Presented by Fitsum Okubu. Introduction Introduction Graphics Graphics Methods and Variables Methods and Variables Events Events Decision.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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.
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
Applications Development
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
25/2/00SEM107 - © Kamin & ReddyClass 9 - HTML - 1 Class 9 - HTML r Creating a personal web page r Structure of HTML documents r HTML tags r The APPLET.
2/5/00SEM107 © Kamin & Reddy Review -1 Class 19 - Review r This lecture contains a selection of slides from previous lectures, giving the “high points”
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Objects and Classes Chapter Nine. Definition “an object is a combination of some data (variables) and some actions (methods)”. Hopefully the data and.
Applets. Internet/WWW How does it work? Internet/WWW.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
CSI 3125, Preliminaries, page 1 Applet. CSI 3125, Preliminaries, page 2 Graphics Methods public abstract void drawString(String str, int x, int y): is.
Java Overview  Design goals & features  platform independence, portable, secure, simple, object-oriented, …  Programming models  applications vs. applets.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Creating a Java Application and Applet
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.
JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Applet: An applet is a java program that is transmitted over the network from the server to client & executed within clients browser. Applets are used.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
User Interface Programming In Java
Java Programming: Guided Learning with Early Objects
UNIT-5.
CSC 551: Web Programming Spring 2004
CSC 551: Web Programming Spring 2004
CSC 551: Web Programming Spring 2004
Presentation transcript:

1 CSC 551: Web Programming Spring 2004 Java Applets  Java vs. C++  instance vs. class variables, primitive vs. reference types, inheritance  graphical applets  Graphics object: drawString, drawLine, drawOval, drawRect, …  double buffering  GUI applets  GUI elements, layout, event handling

2 Java vs. C++ Java syntax borrows from C++ (and C)  primitive types: same as C++, but sizes are set byte (8 bits) char (16 bits) short (16 bits) int (32 bits) long (64 bits) float (32 bits) double (64 bits) boolean  variables, assignments, arithmetic & relational operators: same as C++  control structures: same as C++, but no goto  functions: similar to C++, but must belong to class & must specify public/private in Java, every variable & method belongs to a class  as in C++, by default each object has its own copies of data fields thus, known as instance variables  as in C++, a variables declared static are shared by all class objects thus, known as class variables  similarly, can have a static method ( class method ) can only operate on class variables, accessible from the class itself class Math { public static final double PI = ;// access as Math.PI public static double sqrt(double num) {... }// access as in Math.sqrt(9.0)... }

3 Primitive vs. reference types primitive types are handled exactly as in C++  space for a primitive object is implicitly allocated  variable refers to the actual data (stored on the stack) reference types (classes) are handled differently  space for a reference object must be explicitly allocated using new  variable refers to a pointer to the data (which is stored in the heap) Note: unlike with C++, programmer is not responsible for deleting dynamic objects JVM performs automatic garbage collection to reclaim unused memory Java only provides by-value parameter passing  but reference objects are implemented as pointers to dynamic memory  resulting behavior mimics by-reference public void Init(int[] nums) { for (int i = 0; i < nums.length; i++) { nums[i] = 0; } ______________________________ int nums[] = new int[10]; Init(nums);

4 Java libraries String class (automatically loaded from java.lang ) int length() char charAt(index) int indexOf(substring) String substring(start, end) String toUpperCase() boolean equals(Object)... Array class (automatically loaded from java.lang ) int length instance variable Type [](index)operator String toString()... Java provides extensive libraries of data structures & algorithms java.util  DateRandomTimer ArrayListLinkedListStack TreeSetHashSet TreeMapHashMap String str = "foo" String str = new String("foo"); int[] nums = {1,2,3,4,5}; int[] nums = new int[10];

5 Applet behavior recall  the init method is called when the applet is first loaded useful for initializing variables & objects  the paint method is called immediately after init, and whenever the applet needs to be redrawn (e.g., after window resized or obscured) when paint is called, it is given the default Graphics object  Graphics methods include void drawString(String msg, int x, int y) void setColor(Color color) Color class is predefined, constants include: Color.red, Color.blue, Color.black,...

6 Hello again import java.awt.*; import java.applet.*; import java.util.Random; /** * This class displays lots of "Hello world!"s on the applet window. */ public class HelloWorld2 extends Applet { private static final int NUM_WORDS=100; private static final Color[] colors = {Color.black,Color.red,Color.blue,Color.green,Color.yellow}; private static Random randy; private int RandomInRange(int low, int high) { return (Math.abs(randy.nextInt()) % (high-low+1)) + low; } public void init() { randy = new Random(); } public void paint(Graphics g) { for (int i = 0; i < NUM_WORDS; i++) { int x = RandomInRange(1, 140); int y = RandomInRange(10, 200); g.setColor(colors[RandomInRange(0,4)]); g.drawString("Hello world!", x, y); } store colors in an array pick random index and change color using setColor You must use a Java-enabled browser to view this applet. view page in browser Random class provides methods for generating random values override init method to allocate & initialize (similar to a constructor)

7 Parameters & applet dimensions recall:  can specify parameters in the HTML document using tags  access the parameter values (based on name) using getParameter method can also access the dimensions of an applet using a Dimension object Dimension dim = getSize(); // stores applet dimensions can then access applet height via dim.height can then access applet width via dim.width

8 Adaptive hello import java.awt.*; import java.applet.*; import java.util.Random; /** * This class displays lots of "Hello world!"s on the applet window. */ public class HelloWorld3 extends Applet { private static final Color[] colors = {Color.black,Color.red,Color.blue,Color.green,Color.yellow}; private static Random randy; private Dimension dim; private int numReps; private int RandomInRange(int low, int high) { return (Math.abs(randy.nextInt()) % (high-low+1)) + low; } public void init() { randy = new Random(); dim = getSize(); numReps = Integer.parseInt(getParameter("reps")); } public void paint(Graphics g) { for (int i = 0; i < numReps; i++) { int x = RandomInRange(1, dim.width-60); int y = RandomInRange(10, dim.height); g.setColor(colors[RandomInRange(0,4)]); g.drawString("Hello world!", x, y); } getParameter accesses the values of the parameters here, specify number of reps in Web page uses getSize to get dimensions, pick random coords for text within the applet You must use a Java-enabled browser to view this applet. view page in browser

9 Applet graphics in addition to displaying text  can also draw figures on a Graphics object void drawLine(int x1, int y1, int x2, int y2) void drawRect(int x, int y, int width, int height) void fillRect(int x, int y, int width, int height) void drawOval(int x, int y, int width, int height) void fillOval(int x, int y, int width, int height) EXAMPLE: draw a red circle inscribed in a square, then draw random dots (dart pricks)  by counting the number of dots inside vs. outside the circle, can estimate the value of   = 4 * (area of circle/area of square)

10 Graphical applet public class Monte1 extends Applet { private static Random randy; private int NUM_POINTS; private int SIZE; private int RandomInRange(int low, int high) { CODE OMITTED } private double distance(int x1, int y1, int x2, int y2) { CODE OMITTED } public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = Math.min(dim.width, dim.height); } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval(0, 0, SIZE, SIZE); for (int i = 0; i < NUM_POINTS; i++) { int x = RandomInRange(0, SIZE); int y = RandomInRange(0, SIZE); if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) { g.setColor(Color.white); } else { g.setColor(Color.black); } g.drawLine(x, y, x, y); } You must use a Java-enabled browser... view page in browser init method creates random number generator & gets parameters paint method draws a circle and a bunch of random points

11 Double buffering note: paint is called every time the page is brought to the front  in current version of Monte, this means new dots are drawn each time the page is obscured and then brought back to the front  wastes time redrawing  dots are different each time the applet is redrawn the double buffering approach works by keeping an off-screen image  in the init method (which is called when the page loads): draw the figures on a separate, off-screen Graphics object  in the paint method (which is called whenever the page is brought forward): simply display the off-screen image on the screen

12 Buffered applet public class Monte2 extends Applet {... private Image offScreenImage; private Graphics offScreenGraphics;... public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = Math.min(dim.width, dim.height); offScreenImage = createImage(SIZE, SIZE); offScreenGraphics = offScreenImage.getGraphics(); offScreenGraphics.setColor(Color.red); offScreenGraphics.fillOval(0, 0, SIZE, SIZE); for (int i = 0; i < NUM_POINTS; 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); } else { offScreenGraphics.setColor(Color.black); } offScreenGraphics.drawLine(x, y, x, y); } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } You must use a Java-enabled browser... view page in browser init method is called when page is loaded does drawing to a separate, off-screen Graphics object paint is called after init and whenever the applet is revisited Note: don’t see image in progress

13 Better buffering public class Monte3 extends Applet {... public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = Math.min(dim.width, dim.height); } public void paint(Graphics g) { if (offScreenImage == null) { offScreenImage = createImage(SIZE, SIZE); offScreenGraphics = offScreenImage.getGraphics(); offScreenGraphics.setColor(Color.red); g.setColor(Color.red); offScreenGraphics.fillOval(0, 0, SIZE, SIZE); g.fillOval(0, 0, SIZE, SIZE); for (int i = 0; i < NUM_POINTS; 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); } else { offScreenGraphics.setColor(Color.black); g.setColor(Color.black); } offScreenGraphics.drawLine(x, y, x, y); g.drawLine(x, y, x, y); } else { g.drawImage(offScreenImage, 0, 0, null); } view page in browser if want to see image as it is drawn, must be done in paint when first loaded, have paint draw on the graphics screen and also to an off- screen buffer on subsequent repaints, simply redraw the contents of the off-screen buffer

14 GUI elements in applets Java has extensive library support for GUIs (Graphical User Interfaces)  has elements corresponding to HTML buttons, text boxes, text areas, … each element must be created and explicitly added to the applet nameLabel = new Label("User's name"); add(nameLabel); nameField = new TextField(20); nameField.setValue("Dave Reed"); add(nameField); Java provides several classes for controlling layout  FlowLayout is default  BorderLayout allows placement of elements around the borders of the applet  a Panel can contain numerous elements

15 Text boxes public class Monte4 extends Applet {... private Label insideLabel; private TextField insideField; private Label outsideLabel; private TextField outsideField; public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = Math.min(dim.width, dim.height); setLayout(new BorderLayout()); Panel p = new Panel(); insideLabel = new Label("Inside:"); p.add(insideLabel); insideField = new TextField(5); p.add(insideField); outsideLabel = new Label("Outside:"); p.add(outsideLabel); outsideField = new TextField(5); p.add(outsideField); add(p, BorderLayout.SOUTH); } public void paint(Graphics g) {... insideField.setText("0"); outsideField.setText("0");... if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) { g.setColor(Color.white); int value = Integer.parseInt(insideField.getText())+1; insideField.setText(""+value); } else { g.setColor(Color.black); int value = Integer.parseInt(outsideField.getText())+1; outsideField.setText(""+value); }... } view page in browser

16 Event handling in order to handle events (e.g., text changes, button clicks), can use the event delegation model  must specify that the class implements the ActionListener interface public class Monte6 extends Applet implements ActionListener  each source of events must be registered within the applet dotButton = new Button("Click to generate dots"); dotButton.addActionListener();  must have an actionPerformed method to handle events public void actionPerformed(ActionEvent e) { if (e.getSource() == dotButton) { drawDots(); }

17 ActionListener import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.Random; public class Monte5 extends Applet implements ActionListener {... private Button dotButton; public void init() { randy = new Random(); NUM_POINTS = Integer.parseInt(getParameter("points")); Dimension dim = getSize(); SIZE = dim.width; setLayout(new BorderLayout()); dotButton = new Button("Click to generate dots"); dotButton.addActionListener(this); add(dotButton, BorderLayout.SOUTH); drawCircle(); } view page in browser public void drawCircle() { CODE FOR DRAWING CIRCLE } public void drawDots() { drawCircle(); Graphics g = getGraphics(); for (int i = 0; i < NUM_POINTS; i++) { CODE FOR DRAWING DOTS } public void paint(Graphics g) { g.drawImage(offScreenImage, 0, 0, null); } public void actionPerformed(ActionEvent e) { if (e.getSource() == dotButton) { drawDots(); }

18 Applet examples The Java Boutique has lots of sample applets with source code  Graphing Calculator Graphing Calculator  Mandlebrot Set Mandlebrot Set  front-end front-end  Web search front-end Web search front-end  Java Tetris Java Tetris