CS 66-460
Introduction to Graphical Human Machine Interfaces
Java (Part 2)
MONDAY, APRIL 7, 1997
Instructor: G. Bowden Wise
Rensselaer Polytechnic Institute
Spring 1997
Java supports to styles of comments, both borrowed from C and C++:
// this is a comment // this is a second comment
/* This is a long comment. Which is useful when you have lots of text spanning several paragraphs. */
Integers
byte 1 byte [-128, +128] short 2 bytes [-32,768, +32,768] int 4 bytes [-2,147,483,648, +2,147,483,647] long 8 bytes [-9,223,372,036,854,775,808L, +9,223,372,036,854,775,808L]
Floating Point Numbers
float 4 bytes +- 3.40282347E+38F (7 significant digits) double 8 bytes +- 1.79769313486231570E+308 (15 significant digits)
Characters
char 2 bytes UNICODE
Boolean
boolean 1 byte true, false
In general, binary operations on numeric types are converted to the largest type when there are variables of mixed numeric types
Java will convert operands in the following order:
Conversions from a larger type to a smaller one require an explicit cast:
double x = 9.997; int n = x; // compile time error int n = (int) x; // ok: explicit cast
Java allows assignments from one type to another provided the resulting variable is large enough:
byte .. short .. int .. long .. float .. doubleYou can always assign a variable of a type that is to the left to the type on its right in the above list.
Java does not allow boolean values to be converted to any numeric types. C/C++ programmers may find this a nuisance, no longer can you do this:
// function foo() returns an int if ( foo(a) ) { }instead you must do this:
if ( foo(a) != 0 ) { }
Java does not allow assignments within boolean expressions. It is not
possible to do this:
if ( a = 10 ) { }
class MyClass { static final double e=1.602e-19; public static void main (String args[]) { System.out.println ("fundamental electron charge: " + e); } }
private static final double e=1.602e-19;
int i; char c, d; // comments are helpful double amount; boolean stopped; // is the simulation stopped?
int i; // declaration i = 100; // initialization
int i = 100; char c = 'A'; char a = '\u0041'; // decimal 65 is ASCII 'A'
1 ++ arithmetic R pre or post increment -- arithmetic R pre or post decrement +, - arithmetic R unary plus or minus \~ integral R bitwise complement (unary) ! boolean R logical complement (unary) (type) any R cast 2 *, /, \% arithmetic L multiplication, division, modulus 3 +, - arithmetic L addition, subtraction + String L concatenation 4 << integral L left shift >> integral L right shift with sign extension >>> integral L right shift with zero extension 5 <, <= arithmetic L less than, less than or equal >, >= arithmetic L greater than, greater than or equal instanceof object, type L type comparison 6 == primitive L equal (same values) != primitive L not equals (different values) == object L equal (same objects) != object L not equal (differnt objects) 7 & integral L bitwise AND & boolean L boolean AND 8 ^ integral L bitwise XOR ^ boolean L boolean XOR
9 | integral L bitwise OR | boolean L boolean OR 10 && boolean L conditional AND 11 || boolean L conditional OR 12 ?: boolean,any,any R conditiional (ternary) assignment 13 = variable, any R assignment *=, /= variable, any R assignment with operation \%= +=, -= <<=, >>= >>>= &=, ^= |=
if statements:
if (yourSales >= target) quotaMet = true;or use blocks
if (yourSales >= target) { quotaMet = true; bonus = 1000; }
if () else statements:
if (yourSales >= target) quotaMet = true; else quotaMet = false;or use blocks
if (yourSales > target) { quotaMet = true; bonus = 1000; } else if (yourSales == target) { quotaMet = true; bonus = 0; } else { quotaMet = false; paycut = -1000; }
while statements:
while (balance < goal) balance += 10;or use a block:
while (balance < goal) { amt = 10; balance += amt; }
do statements:
do { amt = 10; balance += amt; } while (balance < goal)
for and while statements:
for (int i=0; i < 10; i++) System.out.println ("i: " + i); while (i < 10) System.out.println ("i: " + i++);with blocks:
for (int i=0; i < 10; i++) { sum += i; System.out.println ("i: " + i + "sum: " + sum); } while (i < 10) { sum += i; System.out.println ("i: " + i + "sum: " + sum); i++; }
switch statements:
import jave.util.Date.*; Date today = new Date(); String day = ""; switch (today.getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break; } System.out.println ("Today is: " + day);
Un-labeled break statements:
while (years <= 100) { balance = (balance + payment) * (1 + interest); if (balance > goal) break; years++; }
Labeled break statements:
test: if (check(i)) { for (int j=0; j < 10; j++) { for (k=0; k < 10; k++) { if (a[i][j] == null) break test; } } }
Un-labeled continue statements are used to break to the top of a loop:
while (years <= 100) { balance = (balance + payment) * (1 + interest); if (balance == 500) { balance = 550; continue; } years++; }
Labeled continue statements:
Examples:
int[] I = new int[100]; for (int i=0; i < 100; i++) I[i] = i; // fill array with 0 to 99 int lookupTable[] = { 1, 10, 15, 20, 25, 30};
public class ShellSort { public static void sort(int[] a) { int n = a.length; int incr = n / 2; while (incr >= 1) { for (int i=incr; i < n; i++) { int temp = a[i]; int j = i; while ( j>= i && temp < a[j-incr]) { a[j] = a[j-incr]; j -= incr; } a[j] = temp; } incr /= 2; } }
public static void main (String[] args) { int[] a = new int [10]; for (int i=0; i < a.length; i++) a[i] = (int) (Math.random() * 100); System.out.print ("Unsorted: "); for (int i=0; i < a.length; i++) System.out.print (a[i] + " "); System.out.println (" "); sort (a); System.out.print ("Sorted: "); for (int i=0; i < a.length; i++) System.out.print (a[i] + " "); System.out.println (" "); } }
public class LotteryDrawing { public static int[] drawing (int high, int number) { int numbers[] = new int [high]; int result [] = new int [number]; // fill in array with numbers 1 2 3 ... high for (int i=0; i < high; i++) numbers[i] = i+1; for (int i=0; i < number; i++) { int j = (int) (Math.random() * (high - i)); result[i] = numbers[j]; numbers[j] = numbers[high - 1 - i]; } return result; } public static void main(String[] args) { int high = 50; int number = 5; int[] a = drawing (high, number); for (int i=0; i < a.length; i++) System.out.println (a[i]); } }
String empty = ""; String hello = "Hello"; // concatenation String hello2 = hello + " world"; // substrings String world = hello2.substring(6, 5); // characters: char w = world.charAt(0); // cannot change individual characters // compile time error world[0] = 'W'; // but can replace whole string: world = "World"; // for comparing two strings: if (world.equals(hello2)) // DO NOT USE THE == operators // it will compare the addresses of the objects if ( world == hello2 )
Example:
class ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) { dest.append(source.charAt(i)); } return dest.toString(); } } public class Reverse { static public void main (String[] args) { String s = "Reverse Me"; String r = ReverseString.reverseIt (s); System.out.println (" String: " + s); System.out.println ("Reversed: " + r); } }
Other data structures are available from the java.util package:
Procedural programming
Object-oriented programming
One definition of an object-oriented langage is that the langauge provides support for the following
The process of deferring of which method to call is called late binding or dynamic binding
There are three common relationships among classes:
What goes in a class:
Within each section, we can have:
When implementing classes, you implement:
Java provides 5 levels of access control for class members - both data and methods:
When to use:
When we define a class, we specify
In general, a class declaration in Java looks like:
[modifiers] class ClassName [extends SuperClass] [implements InterfaceNames] { }
When we define class data members, we specify
In general, a class data member in Java looks like:
accessSpecifier] [static] [final] [volatile] type variableName
static final double PI = 3.14159; // constant private double width; // private instance data
When we define class methods, we specify
In general, a class data member in Java looks like:
[accessSpecifier] [static] [abstract] [final] [native] [synchronized] returnType methodName ([paramlist]) [throws exceptionsList]
Examples:
public static int getX() { return x; } public double area() { return width * height; } public abstract void draw (); public void OpenFile () throws IOException { ... } public void sort (int[] a) { ... }
Example: a hierarchy of shapes with methods for:
abstract class Shape { public Shape (String name) { shName = name; } public abstract double area(); public abstract double circumference(); public String getName () { return shName; } private String shName; } class Circle extends Shape { public Circle () { super("Circle"); this.r = 1.0; } public Circle (double r) { super("Circle"); this.r = r; } public double area() { return java.lang.Math.PI * r * r; } public double circumference() { return 2 * java.lang.Math.PI * r; } public double getRadius() { return r; } protected double r; } class Rectangle extends Shape { public Rectangle () { super("Rectangle"); this.w = 1.0; this.h = 1.0; } public Rectangle (double w, double h) { super ("Rectangle"); this.w = w; this.h = h; } public double area () { return w*h; } public double circumference() { return 2*(w + h); } public double getWidth() { return w; } public double getHeight() { return h; } private double w; private double h; }
public class shapes { public static void main(String args[]) { Shape[] shapes = new Shape[3]; shapes[0] = new Circle (2.0); shapes[1] = new Rectangle(); shapes[2] = new Rectangle(4.0, 2.0); double total_area = 0; for (int i=0; i < shapes.length; i++) { total_area += shapes[i].area(); System.out.println (shapes[i].getName() + ": area= " + shapes[i].area() + ", circumference= " + shapes[i].circumference()); } System.out.println ("Total area = " + total_area); } }
$javac shapes.java
$ java shapes Circle: area= 12.5664, circumference= 12.5664 Rectangle: area= 1, circumference= 4 Rectangle: area= 8, circumference= 12 Total area = 21.5664 $
public interface Drawable { public void setColor (Color t); public void setPosition (double x, double y); public void draw (DrawWindow dw); }
Example:
public class DrawableRectangle extends Rectangle implements Drawable { public DrawableRectangle ( double w, double h) { super(w,h); } public void setColor (Color t) { this.c = t; } public void setPosition (double x, double y) { this.x=x; this.y = y; } public void draw (DrawWindow dw) { dw.drawRect (x, y, w, g, c); } private Color c; private double x, y; }
To create and view an applet:
$javac MyApplet.java
$appletviewer myapplet
<APPLET CODE="HelloWorldApp.class" WIDTH=150 HEIGHT=25></APPLET>
Required HTML tags:
which must have the following attributes:
Optional attributes of the APPLET tag:
To pass parameters to applets we use the PARAM tag which has two attributes:
<APPLET CODE="SampleForm.class" WIDTH=150 HEIGHT=25> <PARAM NAME="Name" VALUE="Joe"> <PARAM NAME="Address" VALUE="1234 Main"> <PARAM NAME="Amount" VALUE="50.00"> </APPLET>
There are four methods in the Applet class that give you the framework on which to build any serious applet:
Because applets are designed to be loaded from a remote site and then executed locally, there are a number of security restrictions for applets.
In general, applets are not allowed to do things like:
Different Web browsers may relax some of these restrictions. Netscape provides less security when loading an applet from a local file than it does for loading an applet via a URL, for example.
In addition, the appletviewer does not impose most of the above restrictions.
Parameters may be passed to an applet from the HTML file in which the applet has been embedded.
Here is an example:
<HTML> <HEAD> <TITLE> An Applet with Parameters </TITLE> </HEAD> <BODY> <APPLET CODE="SampleForm.class" WIDTH=150 HEIGHT=25> <PARAM NAME="Name" VALUE="Joe"> <PARAM NAME="Address" VALUE="1234 Main"> <PARAM NAME="Amount" VALUE="50.00"> </APPLET> </BODY> </HTML>
These values are usually retrieved in the applet's init() method by calling the applet's getParameter() method:
String name = getParameter("name");Note that the parameters in the getParameter method and the PARAM tag must match exactly.
class CalculatorApplet extends Applet { public void init() { add(new Button ("Calculator"); } public boolean action (Event evt, Object arg) { if (arg.equals ("Calculator")) { if (calc.isShowing()) calc.hide(); else calc.show(); } else super.action (evt, arg); return true; } Frame calc = new Calculator(); }
The Abstract Windowing Toolkit is provided by the java.awt package.
The AWT is divided into three categories:
The AWT provides a number of classes for graphics:
The AWT provides a number of GUI components:
The AWT provides a class for grouping checkboxes:
The AWT provides classes for menus:
boolean handleEvent (Event evt);
boolean action (Event evt, Object arg);
return super.action (evt, arg); or return super.handleEvent (evt, arg);
import java.awt.*; import java.applet.*; public class GUI1 extends Applet { public void init() { b1 = new Button ("Press me"); field1 = new TextField ("Welcome!", 20); setLayout (new GridLayout (2, 1)); add (b1); add (field1); } public boolean action (Event event, Object arg) { if (event.target == b1) { field1.setText ("Thank you!!!" ); return true; } else { return super.action (event,arg); } } private Button b1; private TextField field1; }