programming in java java applets - homepage...
TRANSCRIPT
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Applets
Programming in Java
Java Applets
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
CGI - Common Gateway Interface
Internet
Operating System
Browser
HTMLCGI
Application Program
Application
Client WebServer
Applications
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Applications and Applets
Internet
Operating System
Browser
Java
Applet
HTML
CGI
Application Program
Application
Client WebServer
Java
Applications
Application
Server
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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.)
Easy upgrading using "J": Applet →→→→ JApplet
Button →→→→ JButton
AWT and Swing are part of the JFC (Java Foundation Classes)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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 / Subpackagesimport java.awt.Color;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Font;
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Classes, Packages
Component
Container
Panel
Applet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class JApplet
Component
Container
Panel
Applet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
JApplet
Class JApplet:An extended version of java.applet.Applet
that adds support for the JFC/Swing
component architecture.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Classes, Packages
public class Name extends java.applet.Applet
{
...
}
Syntax:
imported package
class
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Methods
Java Applets
Methods that are automatically called
(implicit call)
cleanup (before exiting)void destroy()
stop the appletvoid stop()
repaint screen: call paint() for updatevoid repaint()
paint screen: display text, graphicsvoid paint(Graphics g)
start the applet when loading HTML page
(e.g. start animation)
void start()
Initialization:
Set up colors, fonts, etc. when first loaded
void init()
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Hello World Applet
import java.awt.Graphics;
public class HelloWorldApp extends java.applet.Applet
{
public void paint (Graphics g)
{
g.drawString("Hello World!", 40, 20);
}
}
Example Source Program "Hello World"
stored in:HelloWorldApp.java
compiled with:javac HelloWorldApp.java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
AWT
The java.awt.Graphics class
Coordinate System:x
y
origin
Unit: pixel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Hello World Applet
<HTML>
<HEAD>
<TITLE>Hallo World Applet</TITLE>
</HEAD>
<BODY>
<APPLET CODE= "HelloWorldApp.class"
WIDTH = "210" HEIGHT = "50">
</APPLET>
</BODY>
</HTML>
Example Source Program "Hello World"
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Hello World Applet
Object Tag:To address these issues, HTML 4 introduces the OBJECT element, which
offers an all-purpose solution to generic object inclusion.
The new OBJECT element thus subsumes some of the tasks carried out by
existing elements:
OBJECTIFRAMEAnother HTML document
OBJECTAPPLET (deprecated)Applet
OBJECTIMGImage
Generic elementSpecific elementType of inclusion
The chart indicates that each type of inclusion has a specific and a general
solution. The generic OBJECT element 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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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);
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Methods
Further MethodsDetermines if this applet is active.boolean
isActive()
Returns information about this applet.String
getAppletInfo()
Plays the audio clip at the specified
absolute URL.
void
play(URL url)
Returns the AudioClip object specified by
the URL argument.
AudioClip
getAudioClip(URL url)
Returns an Image object that can then be
painted on the screen.
Image
getImage(URL url)
Gets the base URL.URL
getCodeBase()
Returns the value of the named parameter
in the HTML tag.
public String
getParameter(String name)
Requests that the argument string be
displayed in the "status window (bar)".
void
showStatus(String msg)
Ref.: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Hello World Applet using Parameters
<APPLET CODE = filename or URL>
<PARAM NAME = "name" VALUE = "value">
...
</APPLET>
Transfering Parameters from HTML to Applet
Check for Null Reference:
...
if (name == null)
...
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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>
continued
With parameters
Without parameters
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Applet using Parameters
with Parameter
without Parameter
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
AWT
DescriptionMethod
x/y-translationcopyArea(6*int)
rect. in background colorclearRect(int,int,int,int)
filled ArcfillArc(6*int)
ArcdrawArc(6*int)
Oval (including circle)drawOval(int,int,int,int)
x,y-coordinates, numberdrawPolygon(int[],int[],int)
3D Rect. with shadow (y/n)draw3DRect(4*int, boolean)
last 2 int for roundingdrawRoundRect(6*int)
filled rectanglefillRect(int,int,int,int)
x/y-upper left to lower rightdrawRect(int,int,int,int)
x/y-start to x/y-enddrawLine(int,int,int,int)
Documentation
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
AWT - Example: Curve Plotting
<HTML>
<HEAD>
<TITLE>Hallo World Applet</TITLE>
</HEAD>
<BODY>
<APPLET CODE= "CurveApp.class" WIDTH="600" HEIGHT = "200">
</APPLET>
</BODY>
</HTML>
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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, float green, float blue)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Color
The class Color provides a series of static Color-objects that can be used directly:
public static Color green
public static Color yellow
public static Color magenta
public static Color cyan
public static Color orange
public static Color pink
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
Methods to determine the RGB-values of a color-object:
public int getRed()
public int getGreen()
public int getBlue()
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Color Methods
Set the foreground colorsetForeground (Color)
Set the background colorsetBackground (Color)
Set the current colorsetcolor(Color)
DescriptionMethods
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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);
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
System Colors
public final class SystemColor:
A class to encapsulate symbolic colors representing the color of native
GUI objects on 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.
The color rendered for the text of control panels and
control objects, such as pushbuttons. SystemColor.controlText
The color rendered for the background of scrollbars. SystemColor.scrollbar
The color rendered for the background of control panels
and control objects, such as pushbuttons. SystemColor.control
The color rendered for the background of interior regions
inside windows. SystemColor.window
The color rendered for the background of the desktop. SystemColor.desktop
Examples:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
AWT Structure
Types of classes and interfaces in package AWT
�Graphics
�Components (Windows, Menus)
�Layout Manager
�Event Handler
� Image Manipulation
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
java.awt
java.awt.Component
CLASSCLASS ABSTRACT CLASSABSTRACT CLASS INTERFACEINTERFACE
extends implements
ComponentComponent
WindowWindow
AWT Structure
ContainerContainer
PanelPanel ScrollPaneScrollPane
ButtonButton LabelLabelCanvasCanvas CheckboxCheckbox
partial listings
ColorColor FontFont ImageImageGraphicsGraphics FontMetricsFontMetrics
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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)
Returns “true” if italicisItalic()
Returns “true” if boldisBold()
Returns “true” if plainisPlain()
Return current styles (0-3)getStyle()
Return current font size (int)getSize()
Return name of font as stringgetName()
DescriptionMethod f.*
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Fonts
Examples:
Font f = new Font("TimesRoman", Font.PLAIN, 72);
g.setFont(f);
g.drawString("This is size 72",10 ,100);
Return current font objectgetFont()
Set font to be usedsetFont()
Set color to be usedsetColor()
Draw a stringdrawString()
DescriptionMethod g.*
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
FontMetrics
FontMetrics (abstract class)
Quality of text and font
Return the descent of the fontgetDescent()
Returns the leading of the fontgetLeading()
Returns the total height of fontgetHeight()
Return the ascent of the fontgetAscent()
Width of char ccharWidth(c)
Return width of string strstringWidth(str)
DescriptionMethod fm.*
2D Text Tutorial
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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);
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
FontMetrics Demo
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Applet Demo
Karnaugh-Veitch Diagramm
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Model-View-Controller
MVC:
Model-View-Controller-Architecture:
� Methodology / design pattern widely used in object-
oriented programming.
� Relates the the user interface (UI) to the underlying data
models.
� Used in program development with Java, Smalltalk, C,
and C++.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
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.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Model-View-Controller
Model
View
Controller