Overview including History and alpha versus beta issues
|
Comparison of Java and Javascript
|
Overall Java Philosophy and Features including security etc.
|
Java Programming Language
|
Object Oriented and Class Structure
|
Exceptions
|
Applet Programming and Threads
|
Abstract Windowing Toolkit
|
Networking and I/O; native classes
|
Futures and HPCC Implications
|
Hot Java is not discussed as beta version not currently available
|
Overview including History and alpha versus beta issues
|
Comparison of Java and Javascript
|
Overall Java Philosophy and Features including security etc.
|
Java Programming Language
|
Object Oriented and Class Structure
|
Exceptions
|
Applet Programming and Threads
|
Abstract Windowing Toolkit
|
Networking and I/O; native classes
|
Futures and HPCC Implications
|
Hot Java is not discussed as beta version not currently available
|
Starts in 1991 by Project Green --- a group in Sun that detaches from the main campus as a semi-autonomous task force focused on operating software for consumer electronic devices such as smart set-top boxes
|
Gosling (creator of Sun NeWS which had major conceptual impact both on current Java and Telescript models) realizes that C++ is not adequate and initiates development of a new language Oak, later renamed as Java.
|
A PDA (Personal Digital Assistant -- codename *7) based on Oak/Java ready in 1993. Green Team incorporates as FirstPerson, Inc.
|
*7 proposal to Time-Warner rejected in 1993. 3DO deal falls through in 1994. FirstPerson, Inc. dissolves.
|
Small group (~30 people, now Java Team) continues development and decides to adapt Oak as a Web technology.
|
An experimental web browser written in Java, called WebRunner and later renamed as HotJava, ready in 1994.
|
Java/HotJava published in April '95.
|
Netscape licences Java in May '95 and builds Java into Netscape 2.0 -- This confuses ownership and open-ness of Java
|
Beta JDK (Java Development Kit) published in summer/fall '95. It is better software but lower functionality than Alpha.
|
First alpha Java books appear in fall '95 such as a popular overview by SAMS and technical book "Java!" by Tim Ritchey, edited by New Riders.
|
Dec 4 1995 Business Week cover story on "Software Revolution --- The Web Changes Everything" exposes Java as a breakthrough force in the expanding Web/Internet. Also points out that "Java as a business" is yet to be defined.
|
In next week, SGI IBM Adobe Macromedia and finally Microsoft adopt/license Java. It appears that Java will be open and should be adopted by open Web community
|
Hooked on Java, by Java developers Arthur van Hoff, Sami Shaio, Orca Starbuck, Addison-Wesley, is the (first) serious (but still rather high-level) book on beta Java. It contains example applets, but not much on programming.
|
Teach Yourself Java in 21 Days, by Laura Lemay and Charles L. Perkins, Sams.net Publishing, is a "how-to" book at the intermediate programming level. It concentrates on applets and windowing more than the object-oriented part of the language.
|
Java in a Nutshell, by David Flanagan, is the language reference book in the familiar O'Reilly series.
|
The Java Programming Language, by Ken Arnold and James Gosling, Addison-Wesley, May 1996, has lots of details on the language basics for intermediate and advanced programmers. It covers threads and i/o packages, but not applets or windowing packages.
|
Java Primer Plus, supercharging Web applications with the Java programming language, by Paul M. Tyma, Gabriel Torok, and Troy Downing, Sams.net, doesn't assume a lot of programming background, has chatty explanations and still covers lots of programming detail.
|
There are four books in the Java Series from SunSoft Press, Prentice-Hall.
-
instant Java*, by John A. Pew, contains multimedia and animation applets for HTML authors. This is not a programming book.
-
Java by example, by Jerry R. Jackson and Alan L. McClellan, covers all key features with examples, but not as much detail about the language.
-
just Java, by Peter van der Linden, for intermediate programmers, gives good explanations of key features without going into every detail.
-
core Java, by Gary Cornell and Cay S. Horstmann, offers detailed coverage of the language and packages for advanced programmers.
|
* this title is great, but what happened to "express Java", "Percolating through Java", and "Java for Drips"?
|
Java omits several rarely used, poorly understood and confusing features of C++ including operator overloading, multiple inheritance, pointers and automatic type coercions.
|
It adds automatic garbage collection which makes dynamic programming easier in Java than in C or C++.
|
It also adds 'Interface' construct, similar to Objective C concept, which often compensates for the lack of multiple inheritance by allowing method calling syntax to be "inherited".
|
The resulting language is familiar as it looks like C++ but is simpler and hence easier to program in.
|
It also results in a much smaller kernel which is suitable for planned Java ports to consumer electronic devices. Base (alpha) interpreter is ~40Kb, libraries and threads add additional 175Kb.
|
Java model can be viewed as a C++ subset, with some dynamic elements inherited from Objective-C (method overloading, garbage collection).
|
Structures, Unions and Functions are absorbed into data and methods of Java classes -- Java is Simple!
|
The strength of Java object-oriented model is not is sophistication but in simplicity and the extensive class library associated with the system (some 250 public classes were released in both alpha and beta).
|
Java class plays also a role of a communication atom in the Web embedding model. Applet classes identify themselves by names in the HTML applet tag. Applet downloads other classes, present in the applet source. Hence, the Java class names play the role of addressing mode for the distributed Java code database.
|
Java language offers a uniform abstract (virtual) machine model which is identical for all platforms.
|
SUN owns the Java Virtual Machine (see online report) -- it is universal while classes can be added by any user
|
Unlike in C/C++ where various integers match the architecture of a physical machine at hand, Java byte, char short, int and long are always of the same size, equal to 8, 16, 16(unicode), 32 and 64 bits, respectively.
-
No header files, preprocessors,#define etc.
-
floating point is always IEEE 754
|
Differences between vendor specific windowing environments (X Windows, MS Windows, Macintosh) are removed in terms of the Abstract Windowing Toolkit (AWT) metaphor.
|
AWT is given by ~60 Java classes (alpha) which offer a universal GUI programming model, portable between UNIX, PC and Mac, and translated automatically to native windowing systems on individual platforms by Java interpreters.
|
Java binaries are shipped across the network and executed on client machines. Security is therefore a critical issue and strongly enforced in Java.
-
Java contains its own networking classes which are designed to be secure
|
Modifications of the C++ model such as eliminating pointer arithmetic and coercion were dictated mainly by the security requirements.
|
Most viruses are based on acquiring access to private/protected sectors of computer memory which is impossible in Java.
|
Java opcodes are executed at the client side by Java interpreter which operates exclusively on the virtual memory. Hence, unless there are security bugs in the Java interpreter itself, the model is safe and users cannot create security holes by incorrectly or maliciously written applets.
|
The byte codes sent across network are verified at the client which prevents evil/corrupted classes from causing problems
|
Java interpreter performs on-the-fly runtime execution of the Java bytecodes which results typically in a satisfactory performance.
|
Support for generating native machine code out of Java bytecodes, viewed as intermediate compiler form, is also provided and useful for performance demanding applications.
|
The performance of the machine code, generated from Java bytecodes, is comparable to that offered by typical C/C++ compilers on the same platform.
|
Several of these concepts are in fact similar as in the OSF/ANDF project. Using ANDF terminology, we would call Java compiler a 'producer', and the machine code generator discussed here, an 'installer'. Default Java working mode doesn't use installers but directly interprets the intermediate form (this mode is supported in ANDF by GAI -- Generalized ANDF Interpreter).
|
ANDF model is in principle applicable to all languages. Java/HotJava system implements ANDF concepts for the Java language.
|
Source code of a Java program consists of one or more compilation units, implemented as files with .java extension.
|
Each compilation unit can contain:
-
a package statement
-
import statements
-
class declarations
-
interface declarations
|
Java compiler (called javac) reads java source and produces a set of binary bytecode files with .class extensions, one for each class declared in the source file. For example, if Foo.java implements Foo and Fred classes, then "javac Foo.java" will generate Foo.class and Fred.class files.
|
Suppose that Foo implements an applet and Fred is an auxiliary class used by Foo. If HotJava/Netscape encounters a tag <APPLET code="Foo.class">, it will download Foo.class and Fred.class files and it will start interpreting bytecodes in Foo.class.
|
Java reserves the following keywords:
|
abstract boolean break byte byvalue case cast
|
catch class const continue default do double
|
else extends final finally float for future generic
|
goto if implements import inner instanceof int
|
interface long native new null operator outer
|
package private protected public rest return
|
short static super switch synchronized this
|
throw throws transient try var void volatile while
|
Note goto is not allowed in Java but its still reserved!
|
Applets should NOT have main method but rather init, stop, paint etc.
|
They should be run through javac compiler getting a .class file as before
|
Create an HTML file (say HelloWorld.HTML in same directory as .class file) and include in this
|
<applet code="Example.class" width=500 height=200 > </applet> in simplest case with no parameters where applet will run in window of given width and height (in pixels)
|
If you have JDK on one's machine, one can run the applet with appletviewer HelloWorld.html
|
Alternatively run Netscape 2.0 essentially anywhere and applet is interpreted and run by Java interpreter built into Netscape.
|
This way we can compile on places with JDK installed but run almost anywhere!
|
Each Java variable or expression has a definite type. Simple types such as integers or booleans are built-in. New composite types can be constructed in terms of classes, arrays and interfaces.
-
Note booleans are either TRUE or FALSE -- they are not 0, 1 ,-1 ...
|
There are 4 integer types: byte, short, int, long of size 8, 16, 32 and 64 bits, respectively.
|
Float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE754.
|
Characters are given by 16bit Unicode charset and represented as short integers.
|
One can use casts such as longint = (long) i;
|
Arrays are "true" or "first class" objects in Java and no pointer arithmetic is supported. Hence, arrays are handled as all other composite objects and its special role is due only to some syntactic sugar inherited from C/C++.
|
An Array is declared as:
|
and created by:
|
or concisely:
-
int vec[] = new int[128];
|
Subscripts are range checked in runtime and so vec[-1] and vec[128] will generate exceptions.
|
Array length can be extracted via the length instance variable, e.g.
-
int len = vec.length will assign len = 128.
|
Arrays of arbitrary objects can be constructed,
-
e.g. Thread myThreadList[] = new Thread[1024];
|
Arrays can have dynamic sizing
-
int sizeofarray = 67;
-
int vec[] = new int[sizeofarray];
|
Java's expressions are very similar to C and the following are valid:
|
2+3
|
(2+3)*i
|
i++ /* equivalent to i = i +1 */
|
(i > 0 ) && (j>0) /* Boolean */
|
i <<1 /* Left shift by 1 binary digit */
|
(i>0) ? true:false /* Boolean */
|
i >>> 2 /* Signed right shift by 2 binary digits */
|
"fred" + "jim" is "fredjim"
|
/* + Equivalent to . in Perl */
|
(a instanceof B) /* True iff object a is of class B */
|
if(some boolean expression) { .. }
|
else if(another boolean) { .. }
|
else { ... }
|
while(any boolean) { /* Do Stuff */ }
|
do { /* What to do */ } while(another boolean);
|
for(expression1; booleanexpression ; expression2) { ...}
|
naturally starts with expression1, applies expression2 at end of each loop, and continues as long as booleanexpression true
|
switch (expression) { /* Just as in C */
|
case Constant1: /* Do following if expression=Constant1 */
|
/* Bunch of Stuff */
|
break;
|
case Constant2: /* Do following if expression=Constant2 */
|
/* Bunch of Stuff */
|
break; /* ....... */
|
default:
|
/* Bunch of Stuff */
|
break;
|
}
|
Suppose we have defined a class called mPoint for a movable point which has position (x,y) Color color and can be moved by amount (dx,dy) at each step
|
mPoint BunchofPoints[2]; /* defines BunchofPoints to be 2 dimensional array of mPoint objects -- it does not instantiate BunchofPoints */
|
FirstPoint = new mPoint(); /* Allocates an instance of mPoint and invokes Constructor of mPoint to Initialize */
|
FirstPoint.dx=5;
|
FirstPoint.dy=5; /* Redefines values of instance variables dx,dy for object FirstPoint */
|
mPoint could be defined by
|
import java.awt.*;
|
public class mPoint {
-
int x, y;
-
int dx = 1, dy = 1;
-
Color color = Color.black;
|
}
|
Methods of identical name to class are special -- they are constructors
|
mPoint() { /* Default Constructor */
|
}
|
We can overload method to define different versions with different numbers and types of arguments
|
mPoint(int x, int y) { /* Constructor to set Specific Initial values */
|
}
|
Note this refers to current object
|
mPoint can have other methods to set its instance variables such as:
|
public void setDelta(int _dx, int _dy) {
|
} /* where we don't need this as used _dx, _dy */
|
Possible ClassModifiers are:
|
abstract -- Contains abstract methods without implementation -- typically such abstract classes have several subclasses that define implementation of methods
|
final -- Cannot have a subclass
|
public -- May be used by code outside the class package and (unix) file must be called ClassName.java where ClassName is unique public class in file
|
private -- this class can only be used within current file
|
friendly(i.e. empty ClassModifier) -- class can be used only within current package
|
synchronizable -- Instances of this class will not have accesses interrupted by any other threads running in parallel
|
paint is an important method in applets which is defined in parent component class as the null method
|
It must be overwritten by any dynamic applets that need to update display.
|
import java.awt.*; // imports all classes in java.awt package -- this applet needs Graphics, Font, Color which could be listed separately
|
public class HelloWorld extends java.applet.Applet {
|
Font f = new Font("TimesRoman",Font.BOLD,36);
|
public void paint(Graphics g) {
|
g.setFont(f);
|
g.setColor(Color.red);
|
g.drawString("Hello world!", 50, 25); }
|
}
|
We can define a new class mRectangle that extends mPoint where (x,y,color) from mPoint are lower left hand corner/color and we add width and height
|
public class mRectangle extends mPoint {
-
int w, h;
-
public mRectangle(int _x, int _y, int _w, int _h) {
-
super(_x, _y); /* call mPoint's constructor */
-
w = _w;
-
h = _h;
-
} /* End mRectangle Constructor */
|
/* overwrite the mPoint's checkBoundry method */
-
public void checkBoundry(Rectangle rect) {
-
int nx = x+dx;
-
int ny = y+dy;
-
if ( (nx < rect.x) || (nx+w >= rect.x+rect.width) ) dx = -dx;
-
if ( (ny < rect.y) || (ny+h >= rect.y+rect.height) ) dy = -dy;
-
}
-
public void paint(Graphics g) { /* Override mPoint Method */
-
g.setColor(color);
-
g.drawRect(x, y, w, h);
-
}
|
}
|
java.lang Contains essential Java classes and is by default imported into every Java file and so import java.lang.* is unnecessary. Thread, Math, Object and Type Wrappers are here
|
java.io contains classes to do I/O. This is not necessary (or even allowed!) for applets which can't do I/O in Netscape!
|
java.util contains various utility classes that didn't make it to java.lang. Date is here as are hashtables
|
java.net contains classes to do network applications. This will be important for any distributed applications
|
java.applet has the classes needed to support applets
|
java.awt has the classes to support windowing -- The Abstract Windows Toolkit
|
java.awt.peer is a secret set of classes with platform dependent details
|
public class Object is the root of the Class hierarchy. Every java class has Object as its ultimate parent and so any object (object with a small o is any instance of any class) can use methods of Object
|
Methods of Object (used as object.Method()) include:
|
clone() Creates a clone of the object
|
equals(another object) compares two objects returning boolean answer
|
getClass() returns a descriptor of type Class (a child of Object) defining class of object
|
toString() returns a String which represents "value" of object. It is expected that each subclass will override this method
|
wait() in various forms is used to cause threads to wait
|
finalize() contains code to perform when object is deleted by system (I.e. garbage collected)
|
Class: A template for an object which contains variables and methods which can be inherited from other superclasses and whose calling sequence and existence can be defined by interfaces
|
Object or Instance: A particular realization of some class; different instances usually have different values for their variables or instances but the same methods
|
Simple types: variables defined by int, char etc. are NOT objects but each has an associated wrapper class which can be used with greater power but lower efficiency
|
Superclass: A class further up in the inheritance tree
|
Subclass: A class further down in the inheritance tree
|
Abstract classes:contain abstract methods which are not implemented and only define interfaces. Subclasses will provide implementations
|
Java supports a hierarchical model of exceptions which allow and indeed require user to supply suitable handlers for any exception that can occur in a Java program
|
Note exceptions that can occur in a method must either be caught (i.e. handled inside method) or thrown (i.e. returned to callee)
|
Thrown exceptions are like returned arguments and are for instance part of interface to a method
|
Exceptions are all (at some level in hierarchy) subclasses of Throwable class
|
method1 {
-
try {
-
} catch (Exception3 e) {
-
}
|
}
|
method2 throws Exception3 {
|
}
|
method3 throws Exception3 {
-
call dividebyzeroorreadfileorsomething;
|
}
|
<applet code="fred.class" codebase="classes" width="widthvalue" height="heightvalue" >
|
Put a bunch of text here to be displayed by browsers such as Netscape 2.0 on Windows 3.1 that do not support Java
|
</applet>
|
One can also include INSIDE <applet > tag, attributes available for <img > tag in conventional HTML. These attributes are
|
Align=texttop which aligns top of applet with top of the tallest text in the line
|
Align=top which aligns top of applet with top of tallest item in the line
|
and align= absmiddle, middle, baseline, bottom, absbottom with similar meaning
|
hspace=num1 allows num1 pixels to either side of applet and surrounding text
|
vspace=num2 allows num2 pixels to top and bottom of applet and surrounding text
|
java.awt has several important classes including Graphics, Color, Font and FontMetrics
|
Graphics class has primitives to construct basic two dimensional images with methods drawString (text), drawLine, drawRect, fillRect, drawRoundRect (for a rectangle with rounded corners!), draw3DRect (to get shadow effect as in buttons), drawPolygon (general polygon), drawOval, fillOval
|
There are also Image, Font, Color operations
|
Graphicsinstance.setFont(particularFont) will set the current Font in the instance Graphicsinstance of graphics class to the value particularFont of class Font. There are several other such Font related methods in the Graphics class
|
The class Font has an important constructor used as in
|
Font particularFont = new Font("TimesRoman",Font.PLAIN,36);
|
where one can use Courier Helvetica etc. instead of Time Roman
|
Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles
|
FontMetrics fm = getFontMetrics(particularFont); // allows one to find out about the font
|
fm.stringWidth("text"); // returns pixel width of string "text"
|
fm.getHeight(); // returns total height of one line of Font
|
Color c = new Color (redvalue, greenvalue, bluevalue); // red/green/bluevalue can be specified as integers in 0.....255 or floating point numbers from 0 to 1.
|
c is generated as a Color in RGB format.
|
graphicsobject.setColor(c); // sets current color in graphicsobject which is used for all subsequent operations
|
graphicsobject.setFont(particularFont); // similarily sets font hereafter as on previous page
|
There are particular Color instances already defined such as
|
Color.white equivalent to Color(255,255,255)
|
Color.black as equivalent to Color(0,0,0)
|
Color.pink as equivalent to Color(255,175,175)
|
This sets background color and initializes applet bounding rectangle to this color
|
public void update(Graphics g) {
|
g.setColor(getBackground());
|
g.fillRect(0,0,width,height));
|
g.setColor(getForeground();
|
paint(g);
|
}
|
getBackground() and getForeground() are methods in component class
|
fillRect() is a method in Graphics class
|
1. Prepare a directory. and cd to this directory.
|
2. Copy Animator.class, ParseException.class, and ImageNotFoundException.class into your directory.
|
3. create a directory audio and put your audio file in it.
|
Your audio files can be called 0.au, 1.au, etc.
-
The background soundtrack could be any .au file.
|
4. create a directory images and put your image files in it.
-
your image files can be called T1.gif, T2.gif, etc.
-
the loading message can be called loading-msg.gif.
|
5. prepare a HTML page which has the following type of applet tag:
|
<applet code=Animator.class width=200 height=200>
|
<param name=imagesource value="images">
|
<param name=endimage value=10>
|
<param name=soundsource value="audio">
|
<param name=soundtrack value=spacemusic.au>
|
<param name=sounds value="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8.au|9.au|0.au">
|
<param name=pause value=200>
|
</applet>
|
the imagesource attribute indicate you put your image files in directory images.
|
the endimage value 10 indicate that you have 10 image files held in
-
T1.gif, T2.gif, ..., to T10.gif
|
The soundsource indicate that you put your sound files in audio directory.
|
The sounds attribute lets you express your audio file sequence.
|
the pause attribute is the pause (ms) between each image frame.
|
There are other parameters which can be set such as:
|
<param name=startup value="loading-msg.gif">
|
This image will show up first to remind user that image is loading.
|
public void run () {
|
float c = 0; // initialize the color array
|
for (int i = 0; i < colors.length; i++) {
|
colors [i] = Color.getHSBColor (c, (float) 1.0, (float) 1.0);
|
c +=.02; }
|
int i = 0; // cycle through the colors
|
while (true) { setForeground (colors [i]);
|
repaint ();
|
i++;
|
try { Thread.sleep(50); }
|
catch (InterruptedException e) { }
|
if (i == color.length) i = 0;
|
} // End while(true)
|
} // end run()
|
The previous statements could be in init() while in paint(), one will construct applet image in offscreenGraphics as opposed to the argument g of paint(). So one would see statements such as:
|
e.g. offscreenGraphics.drawImage(img,10,10,this);
|
Finally at end of paint(), one could transfer the double buffered image to g by
|
g.drawImage(offscreenImage,0,0,this);
|
One would also need to override the update() method by
|
public void update(Graphics g) {
|
paint(g);
|
}
|
The Event class has various special class (static) variables defined including
|
Event.F1 -- the F1 key
|
Event.UP The Up arrow etc.
|
The Component class (grandparent of Applet) has a rich set of Event handlers which you should override if you wish to process particular input
|
public boolean mouseDown(Event evt, int x, int y) {
-
anchor = new Point(x,y); // record position of mouse click
-
return true; // must do this
|
}
|
Other handlers are mouseDrag, mouseEnter (enters current component), mouseExit, mouseMove (with its button up), keyUp, keyDown
|
In Java, the GUI (Graphical User Interface) is built hierarchically in terms of Components -- one Component nested inside another starting with the smallest Buttons, including Menus, TextFields etc. and ending with full Window divided into Frames, MenuBars etc.
|
Not all useful Classes are inherited from Component. For instance Menu inherits from MenuComponent (interface) --> MenuItem --> Menu
|
One also needs a set of methods and classes to define the layout of the Components in a particular Panel
|
LayoutManager is a java.awt interface with several particular layout strategies implemented as classes under this interface
|
The Container class has methods to interact with LayoutManager classes
|
In the simplest use of AWT, one could add a Button to an Applet (grandchild of Container) using in the init() method for Applet
|
Button b = new Button("Are You Feeling well");
|
add(b); // add() is a Container method
|
The various added Components are put in the panel by the LayoutManager using order in this they were added
|
A Final critical part of the AWT is the actions generated by these components which are processed by overriding the action() method in Component
|
action(Event e, Object Anyargemightliketoreturn);
|
We define extra events -- such as those connected with scrolling or selecting buttons to those of basic mouse/keyboard
|
Radiobuttons are identical to Checkbox's but grouped so that only one in a group can be on at a time. They use same class for buttons but add CheckboxGroup class
|
CheckboxGroup cbg = new CheckboxGroup(); // cbg is group for one set of radiobuttons
|
add(new Checkbox("Red", cbg, false)); // cbg is second argument!!
|
add(new Checkbox("Green", cbg, false));
|
add(new Checkbox("Blue", cbg, true)); // Only one in group cbg can be true
|
We already discussed handling Mouse and Keyboard Events. These AWT components come with new actions which need to be handled with an action() method in your applet
|
Put action ( a method of class Component) in Container instance that is at lowest possible level so you can customize action to things in that Container
|
action(Event evt, Object arg)'s are looked for in same fashion as exceptions. Scan up Containers looking for a method of this name. Scanning stops when you find an action and that method returns true
|
evt.target holds the object that caused the Event
|
Object Arg returned depends on particular Component invoked
|
There are further evt.id's associated with the various peculiar Components -- see description of class Event for current detailed description.
|
Suppose we have a bunch of buttons in a particular Container saying Red, Green, Blue as we illustrated earlier. Then a good action method would be
|
public boolean action(Event evt, Object arg) {
|
if( evt.target instanceof Button)
-
changeColor((String) arg); // changeColor Supplied by the user processes color defined by text string used in defining buttons
|
return true; // tell runtime that this event fully processed
|
}
|
void changeColor(String bname) { // A suitable user routine to be called by above action
|
if( bname.equals("Red")) setBackground(Color.red);
|
else if (bname.equals("Green")) setBackground(Color.green);
|
else if (bname.equals("Blue")) setBackground(Color.blue);
|
else setBackground(Color.pink); // our favorite color
|
}
|
Layout's can be made very sophisticated using an hierarchical approach
|
setLayout(new GridLayout(1,3,10,5)); // Number of cells in y, Number in x, Horizontal gap, Vertical Gap
|
subpanel1 = new MysubpanelClass(); // Add arguments to make subpanel1 special
|
subpanel2 = new MysubpanelClass();
|
add(Some Simple Component such as a Button);
|
add(subpanel1);
|
add(subpanel2);
|
..........
|
Class MysubpanelClass extends panel { // has constructor
|
MysubpanelClass() { // that includes another layout such as
|
setLayout(new GridLayout(7,7,5,5); // etc.
|
In java.io, there are several classes that throw IOExceptions -- please catch them!
|
The class InputStream is basic and it has methods such as read() skip() (bytes in a stream) available() (bytes remaining in stream) close().
|
InputStreams can be created from memory
|
InputStream s = new ByteArrayInputStream(buffer, 100, 300); // creates a stream of 300 bytes in locations 100 to 399
|
More usefully, they can be created from a UNIX file
|
InputStream s = new FileInputStream("/usr/gcf/greatidea");
|
String line; // Here is a useful example
|
try { URLConnection conn = npacurl.openConnection();
|
conn.connect(); // could set options after creation of conn in above line and before connect method invoked
|
InputStream in = conn.getInputStream(); // establish an InputStream on this connection
|
DataInputStream data = new DataInputStream(new BufferedInputSream(in)); // set up two filters allowing both buffering and line access to InputStream
|
while ((line = data.readline()) != null ) {
-
System.out.println("line"); } // print out line -- obviously put your favorite line processing here
|
} catch (IOException e) { process error }
|
Note one useful exception EOFException which can be caught and remove testing in read loops
|