The Java Foundation Classes


The Java Foundation Classes is the collection of classes java supplies to build graphical
user interface. The collection is dominated by the swing collection of classes. The JFCs
include the older awt package of visual components and packages for processing events.
The collection also houses the 2D package, Drag & Drop and the accessibility API.

The swing and awt classes are all JavaBeans. That means they comply to the JavaBean
specification for interoperability. The swing components use the Model-View-Controller
architecture that was originally developed in SmallTalk. The swing components have a
pluggable look-and-feel. This means they can be set to look like the toolkit of one
platform regardless of what platform they are running on. For example, a swing GUI
running on a Linux machine could be switched to resemble a Window's interface.

Originally Java came with the Abstract Windowing Toolkit (AWT). AWT relied on peer-
based components. This means if you were viewing an awt component running on a Mac
you really would be looking at a Mac toolkit component. There were a number of problems
getting these components to layout properly when an application was ported to different
platforms.

The solution was a new set of widgets that would use one peer-based component on which
all the other components of the GUI were drawn. The fact the GUI is drawn superficially on
one 'heavyweight' peer-based component leads to the swing controllers being described as
'light-weight' and 'peerless'. These light-weight components are written 100% in Java and do
not make any native api calls. The swing approach removed the portability problem.

Imports

The swing components are an extension of the awt components rather than a replacement
for them. The new set of components were derived from the Internet Foundation Classes,
(IFCs) that were originally invented by Netscape. This package was introduced in an
extension package. Sun tacks an x on the end of their java extension packages so swing
comes in a javax package. To import the swing components for use in your application
would require you to add the following import to the top of your code.

Example    import javax. swing.*;

Although swing defines many new event types, the swing components are backwards
compatible with the events defined in awt so a second typical import that is made is as
follows.

Example    import java.awt.event.*;

While we are on the topic of imports, swing also works with the layout managers provided
in awt. Layout managers set the physically layout of components added to a frame according
to a pre-ordained plan. We look at these later. We now notice this adds another import that
typically will be made when you build GUIs.

Example     import java.awt.*;

You will usually see all of these imports at the top of a swing application.
 

JFC API

The following table shows the 5 APIs of the Java Foundation Classes
 
Swing   The swing components make up the majority of the Collection 
AWT   The legacy components along with graphics, image processing
 layout managers and event processing classes 
JAVA 2D   A newer package that enhances the graphical capabilities that 
 were supplied in awt
Accessibility   An API that provides assistive technologies. This api travels with
 the swing collection in the javax.accibility package. Accessibility
 defines interfaces that can make user-interface components more
 accessible.
Drag and Drop  Drag and Drop allows components to be relocated with the mouse
 This package is in the java.wat.dnd package. 

The Swing Packages

Swing components make up the majority of the Java Foundation Classes. The swing
collection are made up off the following 17 packages.
 

 javax.swing                          Provides a set of approximately 100 "lightweight" components that
                                                are portable across platforms. They include the majority of user
                                                interface classes characterized by names starting with a capital 'J'.

 javax.accessibility              Defines interfaces that can be used to link  user-interface components
                                                with assistive technology to improve access to those components.

 javax.swing.border              Provides classes and interface that allow the borders of swing
                                                components to be customized or changed to one of a number
                                                predefined stock selections.

 javax.swing.colorchooser   Supports the JColorChooser component.

javax.swing.event                  This package supplies the swing specific event types and listeners
                                                 There are about 25 swing specific events that behave similarly to
                                                 awt events.

 javax.swing.filechooser      Supports the JFileChooser component.

javax.swing.plaf                     Supports pluggable look-and-feel capabilities. The JFC ships with the
                                                 Window's pluggable look & feel, ( javax.swing.plaf.windows) the Motif
                                                  PL&F (javax.swing.plaf.motif) and the Metal PL&F (javax.swing.plaf.metal).
                                                  Teh Macintosh PL&F is obtainable from the Sun site.
 

 javax.swing.plaf.basic          Provides GUI objects built with the Basic look-and-feel. This is the
                                                  second largest package next to swing with over 40 classes.

 javax.swing.plaf.metal          Provides GUI built with the metal look-and-feel.

 javax.swing.plaf.multi       The multiplexing look and feel allows combinations of auxiliary
                                                 look-and-feels with the default look-and- feel.

 javax.swing.table                Supports the JTable component.

 javax.swing.text                    Provides support for editable and noneditable text components.

 javax.swing.text.html            Provides the class HTMLEditorKit and support for creating HTML
                                                   text editors.

 javax.swing.text.html.parser
                                                   Provides a default HTML parser and support classes.

 javax.swing.text.rtf                Provides the RTFEditorKit class for creating Rich-Text-Format
                                                   text editors.

 javax.swing.tree                    Supports the .JTree class

javax.swing.undo                    Provides support for undo/redo capabilities
 

The swing packages provide a superior, lightweight extension of AWT that enhance
the Java programmers ability to create sophisticated Graphical User Interfaces for
his or her clients.



Abstract Classes, Interfaces & MVC Architecture P.  Komisar

Reference: 'Design Patterns', Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, The JDK
documentation, The Java Certification Guide, Heller & Roberts, 'The Java Language Environment'
James Gosling &Henry McGilton


The Java library classes in general make frequent use of java interfaces and abstract classes.
The visual classes also build on a pattern called the Model View Controller architecture that
was invented and first used in Alan Kaye's SmallTalk programming language. Before studying
the swing components it is good to look at the details of these more exotic programming
structures so when we bump into examples of them we know what they are functionally.

Generic Object Oriented Terminology and Java

The Design Pattern's text quotes Peter Deutsch's definition of aframework as being
"a set of cooperating classes that make up a reusable design for a specific class of software".
In classic OO, the term operation is used to describe what an object does. In java the term
used to describe class behaviour is called the method. An operation's signature, refers to
the method's name, parameters and return value specified by the operation. The set of all
signatures defined by an object's operations is called the interface to the object. An object's
implementation is defined by it's classAn object'stype is the set of requests to which the
object can respond.

This can lead to a little confusion in the initial discussion of java as one can speak of the class'
interface and as well as a special data type defined in java called the interface. Also in Java,
method signature is limited to the name of the method and the number order and type of formal
parameters provided. (The return type, and optional modifiers and throws clauses are not part
part of the signature).
 

The difference Between Class and Type

Following is a quote from the famous book, 'Design Patterns' by Erich Gamma,
Richard Helm,  Ralph Johnson and John Vlissides.

"An object's class defines how the object is implemented. The class defines the object's
  internal state and the implementation of it's operations. In contrast an object's type
  only refers to it's interface, the set of requests to which it can respond. An object can
  have many types, and objects of different classes can have the same type. ... Because
  a class defines the operations an object can perform, it also defines the objects type.
  When we say an object is an instance of a class, we imply that the object supports
  the interface defined by the class."

This says a class embodies the implementation of it's interface which is the set of
operations it defines. The class and it's type (or interface) are really different things.
This is why the quote goes on to say that a class can represent more than one
interface or many different classes can have the same interface.

To illustrate in a Java context a class X might be defined as implementing interfaces
Y and Z. In Java it would look like,

class X implements Y, Z{    }

This class could then be declared and instantiated as type X, Y or Z.

Example               X  x = new X( );    // or
                          Y  y = new X( );    // or
                          Z  z = new X( );

This example shows one class can represent several different types or interfaces.

Now consider two different classes implementing the same interface.

class A implements Runnable{ }
class B implements Runnable{ }

Here two different different classes can be instantiated to the same type.

Example           Runnable a= new A( );
                          Runnable b= new B( );
 

Abstract class

Java has two structures that embody an interface or type without any implementation,
the abstract class and the interface. An abstract class has the main purpose of defining
an interface that will be commonly used by all it's subclasses. The subclasses are given
some or all of the implementation tasks.

Abstract classes may be used in designing a family of related subclasses. A typical pattern
in java, is where an abstract classe implements an interface. For instance AbstractMap
implements Map.

Abstract classes and interfaces will often have default implementations provided in the
Java libraries. For instance Document interface is implemented by AbstractDocument
class. AbstractDocument class in turn is subclassed by DefaultStyledDocument.

Another variation is having a default implementation provided directly for an interface.
An example of this is the class ImageIcon which is a default implementation of the
Icon interface.

Abstract classes in the Java libraries somtimes descend from a concrete class and in turn
spawn other concrete subclasses. In this context the abstract element provides a point
of divergence in the inheritance hierarchy. Subsequent subclasses of this class will all
share this abstract feature but will implement it in unique ways.
 

Technical Specifications of an Abstract Class

In Java an abstract class is any class marked abstract. It may contain zero or more
abstract methods. An abstract method is a method defined without a body. (A method
that has no body defined in curly braces).

abstract void go( );            // no body in curly braces

In the class context, an abstract method must be marked with the abstract keyword.
Often, abstract classes are used to describe a collection of concrete methods
with perhaps only one or two abstract methods defined in the collection. This way
the authors of the abstract class can limit the behavioural changes made to subclasses
and ensure that certain predictable behaviour will be found in all the subclasses that
are created from it.

Abstract classes are designed to be subclassed and cannot themselves be instantiated.
If a subclass of an abstract class doesn't provide implementations for any abstract
methods found in the abstract class, this class also has to be marked abstract.A
method declared abstract cannot also be declared to be private, static, final, native,
strictfp, or synchronized.
 

Interfaces

"an interface is simply a specification of methods that an object declares it implements."

                                                                                                            -James Gosling & Henry McGilton

An interface is one of the three reference types defined in Java. The three are the array,
the class and the interface. As the Gosling quote above shows, an interface is just what
it's name implies, a set of operations a class object can be declared as implementing.
The interface is a kind of an adapter or plugin that brings additional behaviour to a class.
The interface is special, as it is not bound to inheritance structure and can provide a
special behaviour across class hierarchies.

Example

interface Flying { void fly; }

          Hierarchy 1                           Hierarchy 2

          Mammals                                   Fish
           /        \                                      /     \
      dogs      squirrels                   salmon    sailfish

class FlyingSquirrel implements Flying{ // provide an implementation for fly( ) method }
class FlyingSailFish implements Flying{ // provide an implementation for fly( ) method }
 
 
Java Language Interfaces 
  // quoted from 'The Java Language Environment' James Gosling &Henry McGilton

   "Interfaces were introduced to Java to enhance Java's single-inheritance model. The designers 
    of Java decided  that multiple inheritance created too many problems for programmers and 
    compiler writers, and decided that a single inheritance model was better overall. Some of the 
    problems described in the previous discussion on the single-inheritance model are solved in
    a more elegant fashion by the use of interfaces. 

    An interface in the Java language is simply a specification of methods that an object declares 
    it  implements. An interface does not include instance variables or implementation code--only 
    declarations of constants and methods.  The concept of an interface in the Java language was 
    borrowed from the Objective-C concept of a protocol.

     Whereas a class can inherit from only one superclass, a class can implement as many 
     interfaces as it chooses to. Using the examples from the previous discussion, the 
     HashTableEnumerator and VectorEnumerator classes both implement an Enumeration 
     interface that's specific to the characteristics of the HashTable and Vector classes. When 
     you define a new collection class--a Queue class, for instance--you'll also probably define 
     a QueueEnumerator class that implements the Enumeration interface."
.

In Java, an interface is one of the three java reference types. (The other two are the array
and the class). The interface is defined using the interface keyword followed by an identifier
and curly braces containing abstract methods and or constants. These members do not have
to be marked abstract (or for that matter, public) as the members of interfaces are implicitly
abstract and public.
In addition every field declaration in the body of an interface is implicitly static and final
and must be initialized. If the initializer isn't an assigned constant, the variable initializer will
evaluate exactly once at the time the interface is initialized. An example is the Icon interface.

example    public interface Icon{
                    void paint paintIcon(Component c, Graphics g, int x, int y);
                    int getIconHeight( );
                    int get IconWidth( );
                  }

Interfaces intended use was to provide an alternative to multiple inheritance for defining
new types of behaviour for a subclass. A class in java can only inherit from one parent but
can implement any number of interfaces. A class signals it is implementingan interface by
using the implements keyword. Interfaces also provide a means of relating classes which
are not related by inheritance.

Somtimes empty interfaces are used as tagging devices to signal the programming
environment a certain kind of behaviour is needed. An example of this is the Serializable
interface which is empty and does not define any methods.

Just an Interesting Java Detail
 
 
Interfaces may multiply inherit

Hardly ever mentioned in text books, perhaps because there is so much else to talk about,  is 
 the fact that the Java language specification allows multiple inheritance to occur for interface 
 types. By virtue of the fact that interface methods are abstract, having no implementation, 
 some of the types of  problems that arise in class multiple inheritance don't arise. 

// an added note, experimenting with giving the variables of the same name to the parent 
// interfaces to see which one is inherited by the child interface results a novel compiler 
// report saying that   "the reference to s is ambiguous, both variable s in multiple. F and 
// variable s in multiple.M match s" 
     ^
Example

/* Example of  interface multiple inheritance. The example doesn't really do 
     anything except to show multilple inheritance in interfaces is possible */

  interface F{
    char F='f';
    void female( );
    void common_goddess();
    }

  interface M{
    char M='m';
    void male( );
    void common_god( );
    }

  interface C extends F, M {
    void maleOrFemale( );
    char C='c';
    }

   //    the implementation class still has to provide executable code for all
   //    the interface methods, including those of the parent interfaces

  class NewBorn implements C {
    public static void main(String args[]){
    NewBorn nb=new NewBorn( );
    nb.maleOrFemale( ); 
    }

  public void maleOrFemale(){
    System.out.println("Male or Female" );
    System.out.println("Constants defined in the interfaces have the values " +
    F + ", " + M + " and " + C);
    }

  public void female(){};  // stub implementations of other interface methods
  public void male(){};
  public void common_god_goddess(){};
  }
 


public interface Icon         //details from the JDK 1.2.2 API documentation

public interface Icon{
   void paintIcon(Component c, Graphics g, int x, int y);
   int getIconWidth( );
   int getIconHeight( );
   }

A small fixed size picture, typically used to decorate components.
 
 void paintIcon
 (Component c, Graphics g, 
 int x, int y)
 Draw the icon at the specified location.  Icon implementations may use 
 the Component argument to get properties useful for painting, e.g. the 
 foreground or background color.
 int getIconHeight( )   Returns an int specifying the the icon's fixed height.
 int getIconWidth( )   Returns an int specifiying the icon's fixed width.

example
public class J extends K implements Icon{
void paintIcon(Component c, Graphics g, int x, int y){//implementation }
  int getIconHeight( ){//implementation}
  int getIconWidth( ) {//implementation}
 }


Inner Classes   Supplemental

We don't need this material for the course but this is a nice place to put it for reference.


Since JDK 1.1.x, inner classes, also called nested classes, can be declared inside the scope
of some other class. The fully qualified name of the inner class is Outer.Inner. From the class
loaders point of view, the inner class is actually called Outer$Inner. The $ symbol removes
ambiguity between package members and inner classes. It removes conflicts on filing systems
that limit the number of characters that can follow a dot.

Example  public class Outer{
               long z;
                  public class Inner{
                     byte a;
                     }
             }

Example// Starting an inner class instance inside a static method such as main( )

public static void main(String [] args) {
   Outer.Inner in = new Outer( ).new Inner( );
   System.out.println(in.a);
   }

Static Inner Classes

While an inner class has a hidden reference to the outer class, a static inner class, whose
member values are associated with the class rather than an instance of the class, has no such
implied reference. A static inner class can only access static members of the enclosing class.
You can't reference a static inner class without referencing the enclosing class. Really a static
inner class is a top-level (or should we say outer level) class with a modified naming scheme.

Classes Defined inside Methods

Java allows creating classes inside methods. These classes will have the same access as other
members local to the method. An added restriction, the inner classes can only access variables
marked final in the method scope. This step is neccessary as the object created inside the
method is likely to outlive the scope of the method in which case non-final variables would
become invalid.

Anonymous Inner Classes are inner classes without reference. They are used inline where
theyare created. They are most commonly used in event processing. We look at these when
we look at events. Here the inner class is created in the type of of the ActionListener interface
and the requiredmethod definition is provided inside it.

Example  aButtonComponent.addActionListener(
                              new ActionListener( ){
                                          public void actionPerformed(ActionEvent ae){
                                              System.out.println("Button Action");
                                             }
                                        }
                );

// the text is exagerated to show clearly how the anonymous, inner class is
// provided as an argument to the addActionListener( ) method.