Java Applets Programming in Java Java Applets
Java Applets applet= app = application snippet = Anwendungsschnipsel An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. Ref.: Sun Microsystems
CGI - Common Gateway Interface Internet Applications HTML Browser CGI Application Program Operating System Client Application WebServer
Java Applications and Applets Internet Java Applications Java Applet HTML Browser Application Server CGI Application Program Operating System Client Application WebServer
Java Applications and Applets Applet: Java application that runs within a WWW-browser. Java AWT: Abstract Windowing Toolkit Advantages: Defined surface exists (window, graphic environment, event handling) Disadvantages (security): no file access;no communication with other computers; programs cannot be executed;native code cannot be loaded.
AWT vs. Swing APIs Java AWT (Abstract Windowing Toolkit) Package: java.awt GUI functionality (graphical user interface) Component libraries: labels, buttons, textfields, etc. (platform dependent) Helper classes: event handling, layout managers (window layouts), etc. The Swing APIs Package: javax.swing Greater platform independence - portable "look and feel" (buttons, etc.) AWT and Swing are part of the JFC (Java Foundation Classes) Easy upgrading using "J": Applet JApplet Button JButton
Viewing Applets Viewing Applets: a. using a (Java enabled) Browser: load HTML-file (*.html) that will call the applet-file (*.class) from local directory. b. Using the appletviewer (part of the java development kit): appletviewer name.html batch file: appletviewer %1.html
Classes, Packages Classes for Applet Programming java.awt.graphics java.awt.image java.awt.font java.awt.color java.awt.event java.net.url Importing Packages / Subpackages import java.awt.color; import java.awt.*; import java.awt.graphics; import java.awt.font;
Classes, Packages java.lang.object java.awt.component java.awt.container java.awt.panel java.applet.applet Component Container Panel Applet
Class JApplet java.lang.object java.awt.component java.awt.container java.awt.panel java.applet.applet javax.swing.japplet Class JApplet: An extended version of java.applet.applet that adds support for the JFC/Swing component architecture. Component Container Panel Applet JApplet
Classes, Packages Syntax: public class Name extends java.applet.applet {... } imported package class
Methods Java Applets Methods that are automatically called (implicit call) void init() void start() void paint(graphics g) void repaint() void stop() void destroy() Initialization: Set up colors, fonts, etc. when first loaded start the applet when loading HTML page (e.g. start animation) paint screen: display text, graphics repaint screen: call paint() for update stop the applet cleanup (before exiting)
Hello World Applet Example Source Program "Hello World" import java.awt.graphics; public class HelloWorldApp extends java.applet.applet { } public void paint (Graphics g) { g.drawstring("hello World!", 40, 20); } stored in: HelloWorldApp.java compiled with: javac HelloWorldApp.java
AWT The java.awt.graphics class Coordinate System: origin x y Unit: pixel
Hello World Applet Example Source Program "Hello World" <HTML> <HEAD> <TITLE>Hallo World Applet</TITLE> </HEAD> <BODY> <APPLET CODE= "HelloWorldApp.class" WIDTH = "210" HEIGHT = "50"> </APPLET> </BODY> </HTML>
Hello World Applet Object Tag: To address these issues, HTML 4 introduces the OBJECTelement, which offers an all-purpose solution to generic object inclusion. The new OBJECTelement thus subsumes some of the tasks carried out by existing elements: Type of inclusion Image Applet Another HTML document Specific element IMG APPLET(deprecated) IFRAME Generic element OBJECT OBJECT OBJECT The chart indicates that each type of inclusion has a specific and a general solution. The generic OBJECTelement will serve as the solution for implementing future media types. <object codetype="application/java" classid="java:applet.class" width="200" height="250"> </object> http://www.w3.org/tr/rec-html40/struct/objects.html
Hello World Applet Example import java.awt.graphics; import java.awt.font; import java.awt.color; public class HelloWorldApp2 extends java.applet.applet { String str = "Hello World 2"; int w = 300; int h = 80; Font f = new Font ("Arial", Font.BOLD + Font.ITALIC, 48); public void init() { resize(w,h); } } public void paint (Graphics g) { g.setfont(f); g.drawrect(0,0,w-1,h-1); g.setcolor(color.red); g.drawstring(str, 10, 50); } continued
Hello World Applet Example <HTML> <HEAD> <TITLE>Hallo World Applet</TITLE> </HEAD> <BODY> <APPLET CODE= "HelloWorldApp2.class" WIDTH = "350" HEIGHT = "100"> </APPLET> </BODY> </HTML> Object
Hello World Applet Example using Swing import javax.swing.*; import java.awt.*; public class JHWApplet extends JApplet { String msg; } public void init() { msg = "Hello J-World"; } public void paint(graphics g) { g.drawstring(msg, 20, 30); }
Methods Further Methods boolean isactive() String getappletinfo() void showstatus(string msg) public String getparameter(string name) URL getcodebase() Image getimage(url url) AudioClip getaudioclip(url url) void play(url url) Determines if this applet is active. Returns information about this applet. Requests that the argument string be displayed in the "status window (bar)". Returns the value of the named parameter in the HTML tag. Gets the base URL. Returns an Image object that can then be painted on the screen. Returns the AudioClip object specified by the URL argument. Plays the audio clip at the specified absolute URL. Ref.: Sun Microsystems
Hello World Applet using Parameters Transfering Parameters from HTML to Applet <APPLET CODE = filename or URL> <PARAM NAME = "name" VALUE = "value">... </APPLET> Check for Null Reference:... if (name == null)...
Applet using Parameters import java.awt.graphics; import java.awt.font; import java.awt.color; public class HelloWorldApp3 extends java.applet.applet { String text, fontsize; Font f; int w = 300; int h = 80; int thefontsize; public void init() { resize(w,h); this.text = getparameter("text"); if(this.text == null) this.text = "Hello World - Error!"; this.fontsize = getparameter("fontsize"); if (this.fontsize == null) this.thefontsize = 18; else this.thefontsize = Integer.parseInt(fontSize); } continued
Applet using Parameters } public void paint (Graphics g) { Font f = new Font("Arial", Font.BOLD + Font.ITALIC, this.thefontsize); g.setfont(f); g.drawrect(0,0,w-1,h-1); g.setcolor(color.red); g.drawstring(text, 10, 50); } continued
Applet using Parameters <HTML> <HEAD><TITLE>Hallo World Applet</TITLE></HEAD> <BODY> <APPLET CODE="HelloWorldApp3.class" WIDTH="600" HEIGHT="100"> <PARAM NAME="text" VALUE="Hello World, Version 3"> <PARAM NAME="fontSize" VALUE="48"> </APPLET> </BODY> </HTML> With parameters Without parameters continued
Applet using Parameters with Parameter without Parameter
AWT Documentation Method drawline(int,int,int,int) drawrect(int,int,int,int) fillrect(int,int,int,int) drawroundrect(6*int) draw3drect(4*int, boolean) drawpolygon(int[],int[],int) drawoval(int,int,int,int) drawarc(6*int) fillarc(6*int) clearrect(int,int,int,int) copyarea(6*int) Description x/y-start to x/y-end x/y-upper left to lower right filled rectangle last 2 int for rounding 3D Rect. with shadow (y/n) x,y-coordinates, number Oval (including circle) Arc filled Arc rect. in background color x/y-translation
AWT - Example: Curve Plotting import java.awt.*; public class CurveApp extends java.applet.applet { int f(double x) { return (int) ((Math.cos(x/5) + Math.sin(x/7) + 2) * 50); } } public void paint (Graphics g) { for (int x = 0; x < 400; x++) g.drawline(x,f(x),x+1,f(x+1)); } continued
AWT - Example: Curve Plotting <HTML> <HEAD> <TITLE>Hallo World Applet</TITLE> </HEAD> <BODY> <APPLET CODE= "CurveApp.class" WIDTH="600" HEIGHT = "200"> </APPLET> </BODY> </HTML>
Color Class: java.awt.color Standard colors are class variables RGB-Color: RED, GREEN, BLUE (16.7 million colors) Create New Colors: (Integer) Color name= new Color (int red, int green, int blue) (Float) Color name= new Color(float red, floatgreen, float blue)
Color The class Color provides a series of static Color-objects that can be used directly: public static Color white public static Color lightgray public static Color gray public static Color darkgray public static Color black public static Color red public static Color blue public static Color green public static Color yellow public static Color magenta public static Color cyan public static Color orange public static Color pink Methods to determine the RGB-values of a color-object: public int getred() public int getgreen() public int getblue()
Color Methods Methods setcolor(color) setbackground (Color) setforeground (Color) Description Set the current color Set the background color Set the foreground color setcolor (new Color(1.0f, 0.0f, 0.0f)); Color c = new Color (0,255,0); setbackground (c); // RGB green setbackground(color.green); // Standard color green
Graphics g (lamp demo) import java.awt.*; public class Lamp extends java.applet.applet { public void init() { resize(300,300); } public void paint(graphics g) { // the moon g.drawarc (20,20,100,100,90,180); g.drawarc (40,20,60,100,90,180); // the table g.setcolor (Color.orange); g.filloval (0,220,300,100); g.setcolor (Color.black); continued
Graphics g (lamp demo) } // lamp cable g.drawrect (148,0,5,89); // upper arc of lamp g.drawarc (85,87,130,50,62,58); // two lines of the lamp g.drawline (215,177,181,90); g.drawline (85,177,119,90); // the lower oval g.setcolor (Color.yellow); g.filloval (85,157,130,50); // lamp pattern g.setcolor (Color.red); g.filloval (120,100,20,20); g.copyarea (120,100,20,20,40,-7); g.copyarea (120,100,20,20,30,30); g.copyarea (120,100,20,20,-15,35); g.copyarea (120,100,20,20,60,40); }
System Colors public final class SystemColor: A class to encapsulate symbolic colors representing the color ofnative GUI objectson a system. For systems which support the dynamic update of the system colors (when the user changes the colors) the actual RGB values of these symbolic colors will also change dynamically. In order to compare the "current" RGB value of a SystemColor object with a non-symbolic Color object, getrgb should be used rather than equals. Examples: SystemColor.desktop SystemColor.window SystemColor.control SystemColor.controlText SystemColor.scrollbar The color rendered for the background of the desktop. The color rendered for the background of interior regions inside windows. The color rendered for the background of control panels and control objects, such as pushbuttons. The color rendered for the text of control panels and control objects, such as pushbuttons. The color rendered for the background of scrollbars.
AWT Structure Types of classes and interfaces in package AWT Graphics Components (Windows, Menus) Layout Manager Event Handler Image Manipulation
AWT Structure java.awt.component partial listings Component Container Button Canvas Checkbox Label Window Panel ScrollPane java.awt Graphics Color Font Font Image FontMetrics CLASS extends ABSTRACT CLASS implements INTERFACE
Fonts Class: java.awt.font Font types: Courier; TimesRoman; Helvetica, Arial, etc. Font Styles: Font.PLAIN // = 0 Font.BOLD // = 1 Font.ITALIC // = 2 Size: in pixel
Fonts Font styles are constants that can be added: Example: Font.BOLD + Font.ITALIC // bold italic Creating Fonts, Examples: Font f = new Font("TimesRoman", Font.BOLD, 48) Method f.* getname() getsize() getstyle() isplain() isbold() isitalic() Description Return name of font as string Return current font size (int) Return current styles (0-3) Returns true if plain Returns true if bold Returns true if italic
Fonts Examples: Font f = new Font("TimesRoman", Font.PLAIN, 72); g.setfont(f); g.drawstring("this is size 72",10,100); Method g.* drawstring() setcolor() setfont() getfont() Description Draw a string Set color to be used Set font to be used Return current font object
FontMetrics FontMetrics (abstract class) Quality of text and font Method fm.* stringwidth(str) charwidth(c) getascent() getdescent() getleading() getheight() Description Return width of string str Width of char c Return the ascent of the font Return the descent of the font Returns the leading of the font Returns the total height of font 2D Text Tutorial
FontMetrics import java.awt.*; public class Center extends java.applet.applet { public void paint (Graphics g) { Font f = new Font ("TimesRoman", Font.PLAIN, 24); FontMetrics fm; g.setfont(f); fm = getfontmetrics(f); String str = "This text will be centered"; int x = (this.size().width - fm.stringwidth(str)) / 2; int y = (this.size().height - fm.getheight()) / 2; } } g.drawstring(str,x,y);
FontMetrics Demo import java.awt.*; import java.applet.*; public class DrawText extends Applet { public void paint (Graphics g) { // output strings byte byte_text[] = {'H','E','L','L','O'}; char char_text[] = {'h','e','l','l','o'}; String String_text = "\u00c4g"; // fonts Font Arial24 = new Font ("Arial", Font.PLAIN,24); Font Tmsrm72 = new Font ("TimesRoman", Font.PLAIN,72); // font metrics FontMetrics fm; int ascent, descent; int string_width; int char_width; int leading; continued
FontMetrics Demo // simple output methods g.drawbytes (byte_text,0,5,20,20); g.drawchars (char_text,0,5,20,40); g.drawstring ("A complete string",20,60); g.drawstring (Arial24.toString(),20,80); // selecting a font g.setfont (Arial24); g.drawstring ("Now using Arial 24",20,120); // translate origin g.translate (100,250); // select a large font g.setfont(tmsrm72); continued
FontMetrics Demo // font metrics fm = getfontmetrics (Tmsrm72); string_width = fm.stringwidth (String_text); char_width = fm.charwidth ('\u00c4'); ascent = fm.getascent (); descent = fm.getdescent (); leading = fm.getleading (); // draw vertical lines g.drawline (0, - ascent -10, 0, descent + 10); g.drawline (char_width, -ascent, char_width, descent + 10); g.drawline (string_width, - ascent -10, string_width, descent +10); } // draw horzontal lines g.drawline (-10, 0, string_width + 10, 0); g.drawline (-10, -ascent, string_width +10, -ascent); g.drawline (-10, descent, string_width + 10, descent); g.drawline (-10, descent + leading, string_width + 10, descent + leading); } continued
FontMetrics Demo
Applet Demo Karnaugh-Veitch Diagramm
Model-View-Controller MVC: Model-View-Controller-Architecture: Methodology / design pattern widely used in objectoriented programming. Relates the the user interface (UI) to the underlying data models. Used in program development with Java, Smalltalk, C, and C++.
Model-View-Controller The MVC pattern proposes three main components or objects to be used in software development: A Model: represents the underlying, logical structure of data in a software application and the high-level class associated with it. Does not contain information about the user interface. A View: collection of classes representing the elements in the user interface (visual display, possible user responses -buttons, display boxes, etc.) A Controller: represents the classes connecting the model and the view.
Model-View-Controller View Model Controller