The Java Foundation Classes

Peter Komisar   ©   Conestoga College      latest  version  6.0     2010


Classic Object Oriented Terminology


The Java library classes used for GUI building, in general,
make frequent use of Java interfaces and abstract classes.
Before studying the Swing components, these Java data
structures need to be investigated.

Generic Object Oriented Terminology and Java

The Design Pattern's text quotes Peter Deutsch's definition
of a framework 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.
Java uses the term, 'method' to describe
the individual behaviors of the class. 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 of that object. A class is a definition
of what an object implements. An object's
type is the set
of requests to which the object can respond.

We see an object's type and interface both describe the set
of requests an object can reply to.

// the generic 'interface' is the set of signatures that an object
// defines. A similar terms is 'type' which is the set of requests
// to which an object can reply to.

Classic Interface Definitions and Java's Applied Interface Type

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.

In fact, the Java interface is quite like the generic definition
of an interface in that it is used in Java to define a set of
abstract method signatures. 

In practice, a Java interface is a data structure that may define
zero or more abstract methods and zero or more constant
values. 

 
// Java's interface data structure is very similar to the generic,
// object-oriented notion of 'interface'


The Difference Between Class & Object Type

// a class embodies an implementation of an interface definition

Following is a quote from the famous book, 'Design Patterns'
by Erich Gamma, Richard Helm, Ralph Johnson and John
Vlissides which illuminates the functional difference between
a class and an object of a class.

"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 object's type.
When
we say an object is an instance of a class, we imply that the object
supports
the interface defined by the class."

// a class is a blueprint for manufacturing objects. The blueprint encapsulates
// the design while the object supplies the implementation of the design


Paraphrasing, an object has a type, the set of requests to which
it can respond. Because an object's class definition supplies the
implementations of the set of requests to which an object can
respond, it shares the type of the object. When we say an object
is an instance of a class, it is implies the object supports the
interface defined by the class.


An Instance of a Class has the Same Type as the Class

Class Type  ==   Object Type

// as type is the set of methods that the structure defines or responds to


One Class Can Have Many Types &   
// one to many,
Many Classes can Share One Type     
// many to one

Type or interface is a specification that a class implements.
A class can represent more than one interface or many different
classes can have the same interface. An object is a working
version or instance of a class definition that is available to
supply callable versions of the different methods that collectively
are the interface(s) or type(s) that that class defines.

Illustrating Shared Type

Consider three health workers, A,B & C, with different skill sets.
All three are of the type Health worker. All three are type Doctor.
Anyone one of these can be called a Doctor. Here classes
A, B and C share the types doctor (and health worker).

Illustrating Different Classes Sharing a Type
// many classes : one type


A__Health_Worker  B__Health_Worker   C__Health_Worker

|__Doctor         |__Doctor          |__Surgeon
|__Dentist        |__Dentist         |__Doctor
|__Surgeon        |__Nutritionist    |__Administrator

// If we call A in his capacity as a Doctor we shouldn't expect
//  him or her to have his dental drill with him. That is a part of
// a different set of requests

To illustrate one class having many types in an intuitive
fashion consider just A in the above examples just in
terms of the titles A can use.


Example of One Class Having Many Types


We can think of Individual, Mr or Ms. Smith,  in many
different roles which parallels a single class that is able
to have many types.


Types in a Java Context

In Java, type is associated with an object through inheritance
from the parent. (The child enjoys the parent type recursively
back to Object type.) A type can also be associated with a
class by having that class implement one or more interfaces.

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

(We get to the practical aspects of implementing interfaces
shortly. The following is a preview.)


Example

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 may be instantiated
to the same type.

Example

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


While we are talking about interfaces let us take up
how the interface data type is defined in Java.


Interfaces



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

                                              -James Gosling & Henry McGilton

In creating the interface type, the authors of Java have
preserved the generic sense of what an interface is.

 

The Java Interface
// quote 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  . . .

  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 . . . "



Interfaces are a Java Reference Type

In Java, an interface is one of the three reference types. 


Java's Three Reference Types

// we do not count the new Java enum type (JDK1.5) though a new data type is a
// static
  class type so is referenceable only by the class name and is not instantiated.

The three are the array, the class and the interface. As
the Gosling quote above shows, an interface is
a set of
operations a class object can be declared as implementing.

The interface is a kind of an adapter or 'plug-in' that brings
an additional set of 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{ /* implement the fly( ) method  */ }
class FlyingSailFish implements Flying{ /* implement the fly( ) method */ }


An interface is created using the 'interface' keyword. The
keyword is followed by an identifier
and closed curly braces
which contain zero or more abstract methods and zero
or more constants.

The Automatic Modifiers of the Interface

Methods do not have to be marked abstract or public as the
members of interfaces are implicitly abstract and public.

Methods of interfaces must be abstract. A compiler error is
returned if a method of an
interface is defined with a body.

In addition, every field declaration in the body of an interface
is implicitly 'static' and 'final'
and must be initialized to some
value.


Example
  // will not compile unless values are assigned

interface ConstCoord{
     int X;  // assign a value as in int x=3;
     int Y;  // assign a value as in int y=4;

     }

  // this will compile

 interface ConstCoord{
 int X=3;  // assign a value as in int x=3;
 int Y=4;  // assign a value as in int y=4;

 }


The following simple example defines an interface, implements
it and calls some of it's methods  as defined.

Example   

interface Work{
     boolean cutting();
     boolean framing();
     boolean  wire();
     }


class WorkImp implements Work{
public static void main(String[] args){
    WorkImp wi = new WorkImp();
    boolean check=wi.cutting();
    System.out.println("Cutting Inspected: " + check + "\n");    
    System.out.println("Framing Inspected: " +  wi.framing() );
    }

// notice methods must be marked public as per interface definition

public boolean cutting(){
System.out.println("Saw work completed.");
  return true;
 }
public boolean framing(){
  return false;
 }
public boolean wire(){
 return false;
 }
}

Following is a summary of the rules concerning Java interfaces.


Interface Summary


Classes Implementing Interfaces Must Supply Implementations
for the Interface's Methods

When a class implements an interface it must supply method
implementations. The minimal implementation is an empty
stub method. Using stub methods in this fashion is often done
for methods of an interface that a developer is not interested
in implementing. 


interface Lock{
         void secure( );
         }

public class Door implements Lock{
        public void secure( ){ / * empty stub */ }
       // the interface method is implemented as required
       }

The compiler requires the method secure( ) to be public
as interface methods are implicitly public.

Declare an Interface in it's Own Source File to Make it Public

The interface Lock in the above example, cannot be marked
public if it is included with the class source code because of
the restriction, 'that only the 'top-level' class can be public'.

A public interface that will be used by a number of classes
should have it's own source file. On the other hand if an interface
is going to serve locally to a package it might be well to leave it
have default access.

// declare public interfaces, used by many classes, in their own files


Any Number of Interfaces Can Be Implemented

Interfaces were intended to be used 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

implementing an interface by using the 'implements' keyword.
Interfaces also
provide a means of relating classes which are
not related by inheritance.

 

Interfaces as Tagging Devices

Sometimes empty interfaces are used as tagging devices to
signal the programming that a class needs to be treated in a
special way specific to the role it plays in an application.

An example of this is the Serializable interface which is empty
and does not define any methods. Another such interface is
the Remote interface defined in Java's RMI API.

Example

interface Serializable{      } 

// doesn't define any methods, instead is used as a tagging device


Interfaces may multiply inherit

Hardly ever mentioned, probably because it is of little interest,
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 complications associated with class multiple
inheritance don't arise.

The problem of multiply inherited variables is intercepted by
the compiler with an error report such as "the reference to s
is ambiguous, both variable s in multiple. F and variable s in
multiple.M match s".

Code Example Showing Multiple Inheritance using Interfaces

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

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

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

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

    }

   // 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 super interface methods
  public void male(){ };
  }

An Interface Example from the Java Library

Following is the information from the Java Developer Kit
that is provided for the Icon interface used in the Swing API.
An Icon is a small  fixed size picture, typically used to decorate
components.


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( );
   }

Icon Interface Methods
 

 void paintIcon  (Component c,
 Graphics g,

 int x, int y)

Draws the icon at the specified location. The Component argument may be used to get
properties useful for painting, the foreground
or background color.

 int getIconHeight( ) 

 Returns an int specifying the icon's height.

 int getIconWidth( ) 

 Returns an int specifying the icon's width.


Example of a Class implementing the Icon interface

// This class just shows the technical aspects of implementing an interface

import javax.swing.*;
import java.awt.*;

public class JJ implements Icon{

public void paintIcon(Component c, Graphics g, int x, int y){
       // needs a meaningful implementation
       }
public  int getIconHeight(){
       int y=30;
       return y;
       }
public int getIconWidth(){
       int x=50;
       return x;
       }
 }


Abstract Classes


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. (Without a
body here is a method defined without a block
defined by
a pair of closed curly braces.)

Abstract Method Example

abstract void go( );   

// an abstract method has no body represented by a pair of curly braces


Real World Abstract Classes Often Have Few Abstract Methods

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 can't be instantiated and therefore enforce sub-classing.


Abstract Classes Cannot Be Instantiated

Abstract classes are designed to be sub-classed 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.

Rule for Abstract Methods

A method declared abstract cannot also be declared to
be private, static, final, native, strictfp, or synchronized.

The following summarizes the points made above.


Abstract Class Summary


The Abstract Class in Java GUI Libraries

In the Java GUI libraries there are a lot of class names that include
'default' and 'abstract' in their names. The following sections should
help explain why these classes are named as such.

Java we see, has two structures that are able to embody an interface
or type without any implementation,
the abstract class and the interface.
( In other words, both can define method signatures without method
bodies.)

An abstract class has the primary purpose of defining an interface
that will be commonly used by all it's subclasses. The subclasses
are normally given
some or all of the implementation tasks.

Abstract classes may be used in designing a family of related
subclasses. A typical
design approach found in Java, is where
an abstract class implements an interface. For instance

AbstractMap implements Map.


Library Example of An Abstract Class Implementing an Interface

AbstractMap implements Map


A Default Class Descends from an Abstract Class that

implements an Interfaces

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 sub-classed by
DefaultStyledDocument. The
default implementations are
provided for the programmer who doesn't need a highly

customized version of a class and a stock version will
suffice.

Descendancy of DefaultStyledDocument

Object
|
abstract class AbstractDocument implements Document
|
DefaultStyledDocument

// parts of class signature are left out,
// public modifier and Serializable interface

 

Direct Class Implementation of an Interface

Another common design aspect observed in the Java libraries
is where a default implementation is provided directly for an
interface. An example of this is the class ImageIcon
which is a
default implementation of the Icon interface.


Example of a Class Implementation of an Interface

ImageIcon implements Icon


Abstract to Concrete and Back to Abstract

Abstract classes in the Java libraries sometimes 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.

Further subclasses will all share this abstract feature but
may implement it in unique ways.
AbstractButton is an
example of an abstract class that descends from a concrete
parent and in turn is used in an extension to create a concrete
child class.

 
Example            // from JDK1.5 documentation

java.lang.Object
|_java.awt.Component
|_java.awt.Container
|_javax.swing.JComponent // concrete
|_javax.swing.AbstractButton // abstract
|_javax.swing.JButton // concrete


These observations will help to explain the probable context
in which many of the Swing and AWT classes serve.

A complete explanation of the many architectural patterns found in
the Java GUI libraries is found in the study of classic design patterns
which becomes a subject in it's own right.



Inner Classes



We have seen that besides the commoner elements of the
class, such as variables, methods
and constructors, Java
also allows classes to be nested inside each other. In fact
the Swing components make frequent use of inner classes
in event processing. Inner classes
were introduced into the
Java Development kit early after JDK 1.0 in version JDK1.1

It is nice to see links like the following which preserve the
early development of the language.

Changes in JDK 1.1

http://java.sun.com/docs/books/jls/first_edition/html/1.1Update.html


In the programming  language, the fully qualified name of an
inner
class is represented by the following form.

Fully Qualified Name of an Inner Class

outerObjectName.innerObjectName  


Inner Class File Naming

From the class loaders point of view, the inner class is
actually named Outer$Inner. If you look in your file directory
where an inner class is stored, you will see this 'dollar sign'
syntax used in the name of the class file.  For the class loader,
The $
symbol is used to avoid ambiguity between package
members and inner classes. It also avoids
conflicts on filing
systems that limit the number of characters that can follow a
dot.

// blurb on why dot wasn't used in Inner class name notation

The next examples show these features. First we use the
simplest version of an inner outer class combo to show
the files that appear in the directory. Though 'thin' this still
represent a complete example.


Example
 

class Out
             {
       class In{  }
             }  


After compiling the following class files appear in
the current directory.

Example Showing Directory Contents

C:\Java> dir O*s    // Windows

Out$In.class
Out.class

_____________________________

]$ ls O*s                   // Linux
Out.class  Out$In.class


In the next example, an instance variable in class scope
is included in both of the classes.

Example

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

We show how the inner class is instantiated via an
instantiation of the outer class. Note the declaration
has the form 'Outer.Inner'.

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);
       }

This is equivalent to the longer form shown in the following
example.


Example 
    

Outer o= new Outer( );
Outer.Inner i= o.new Inner( );
System.out.println(i.a);


The following example puts the above pieces into a class
with a main( ) method called Outer.

Example 

 public class Outer{
                  long z;
                  public class Inner{
                  byte a = 123;
                  }

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.

Somewhere down the line, newer Java compilers started
to disallow referencing static inner classes via an instance
reference. (Conventional static members can be referenced
by either the instance reference or the class name. )

Referencing Static Inner Classes Via The Class Name

Referencing via the class name as shown in the next
example seems to be the only way that now works for
referencing static inner classes. This is in keeping with
convention where static members are by convention
referenced via the class name to communicate that they
are static members.


Example     

class Earth
           {
           static String moon="Moon";
           // inner class
           static class Rocket
                   {
           // method of inner class
            static public void report( )
                       {
                        System.out.println("In "+ moon + " Orbit"); }
                       }
                  }

class Orbit
           {                      
           public static void main(String []args)
                {
       //  Earth e=new Earth( );
      //  e.Rocket.report( );
      //  new JDKs now don't allow referencing static inner class
      //  via instance reference, rather only by class referencing


                Earth.Rocket.report( );
                }
          }

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 local variables that are marked 'final' in the method
scope.

This step is necessary 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.

// the class is stored on the heap while the method is on the stack
// when the method is 'popped' it's gone but the class on the heap
// may stay refernceable longer

The next code sample demonstrates this point.

Inner Class Inside Methods Only Reference Variables Marked Final

class Oz{
          // Outer class method
          void method( ){
         
// local method variable marked final
            final   byte boo= 3;  
     
    // class inside method
        class Iz{
           Iz(){
           System.out.println("To bee or not to " + boo);
             } // inner constructor ends
           } // inner class ends
          // instantiating inner class invokes referencing of local variable
           new Iz( );
          
        } // outer method ends
    
         // main( ) runner method instantiates outer class
        public static void main(String [] args){
             Oz oz = new Oz( );
         // method call on outer class that instantiates inner class
         oz.method();
         } // main ends
               
     } // outer class ends

OUTPUT    // Linux

[peter@localhost Examples]$ java Oz
To bee or not to 3


But if we remove the final keyword from byte boo we get the
following error report.


OUTPUT  // with final keyword cut or commented out /* final */          

     
[peter@localhost Examples]$ javac Oz.java
Oz.java:8: local variable boo is accessed from within inner class; needs to be declared final
               System.out.println("To bee or not to " + boo);
                                                        ^
1 error
       


The Anonymous Inner Classes



Anonymous inner classes are inner classes defined without
a reference included.  (Any instantiation without an assignment
is anonymous.)  First we define the anonymous part.

A Standard Anonymous Class Object

The following example shows a main method where a class
is instantiated without a reference value. In this case the
reference generated is discarded.  This gives us the meaning
of the 'anonymous' class.


Example
   

public static void main(String [] args) {
                               new World( );  
  // anonymous as the instance is not caught in a reference assignment

                               }

Anonymous Inner Classes are By Convention Defined 'In-Line'.

A further feature of the anonymous, inner classes is that they
are defined 'in-line'. That is, they are defined right where they
are instantiated. They were first  famous for their common use
in GUI event
processing. We again look at the anonymous
inner class when we look at events.

An Example of a Interface Defined 'In-Lined'

To introduce the 'in-line' form we can first show a new
form for implementing an interface. Instead of
using the
typical declaration ' class X implements ActionListener '
a construction
something like an array creation expression
is used.

Notice this approach doesn't involve using a 'class' or
'interface' keyword. The required method implementation
is supplied inside the body that is the class implementation
of the interface.

Example       // no class keyword in the inline form

ActionListener alistener= new ActionListener( ){
  public void actionPerformed(ActionEvent ae){
     System.out.println("Button Action");
     }
 }

In the above example, the inner class is created to the type
of the ActionListener interface. It defines the one required

method defined by the ActionListener interface.

If the reference is not needed we can create this class
anonymously.

In a typical anonymous inner class the instantiation of the
in-lined class takes place inside the argument area of a
method.

Now we can put this whole expression together. Note
there is no reference captured and the whole class definition
is contained inside the arguments of an
addXXXlistener
method. This is the form commonly referred to as the
anonymous inner class.

 

Example

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

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

The Hallmark of the Anonymous Inner Class

The creation results in the following syntax which is the
hallmark of an anonymous inner class.

Syntactical Hallmark of the Anonymous Inner Class

   } ) ;  


Example 

If we repeat Example 2 above but bold the final three
symbols of the statement we see the hallmark curly
brace, round brace, semi-colon combination that
characterizes anonymous inner classes used in this
form.

aButtonComponent.addActionListener(
         new ActionListener( ){
             public void actionPerformed(ActionEvent ae){
             System.out.println("Button Action");
             }
 }
) ; 
// hallmark ending of an 'inline' anonymous inner class



JFCs Overview



To Swing or Not to Swing?

It is true that Swing has been somewhat 'eclipsed' by newer
GUI building sets such as SWT originating with IBM. However,
you can't beat AWT and Swing for having a 'rink side seat', in
Java. AWT and Swing are both built in parts of the Java standard
distributions You can count on these libraries being there to run
with any standard JRE.  Further they will always see refinement
and improvement with each new Java release.

What's new?

"With the 1.4.2 release we provided two new look and feels
for Swing: XP and GTK. Rather than taking a break, in 5.0
we're providing two more look and feels: Synth, a skinnable
look and feel, and Ocean, a new theme for Metal. Beyond
look and feels, we've added printing support to JTable, which
makes it trivial to get a beautiful printed copy of a JTable.
Lastly, after seven years, we've made jFrame.add equivalent
to jFrame.getContentPane().add( )."
                                                                            -JDK 1.5.0 docs

http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#swing


JFC Overview

The Java Foundation Classes is a framework of classes
that is supplied with Java to enable building graphical user
interfaces.
The collection is dominated by the Swing set
of components.
The JFCs include the older AWT package
which contain the original set of visual components as well
as other utility that enable event processing and component
layouts. The collection also houses the 2D package, Drag
& Drop and the Accessibility API.

// JFC are Swing, AWT, 2D, Drag & Drop and Accessibility


Five APIs of the Java Foundation Classes

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 assisting technologies. This  API  travels
 with 
the Swing collection in the  javax.accessibility 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.awt.dnd package. 


Swing and AWT Components are all JavaBeans

Swing and AWT classes are all JavaBeans and will comply with
the JavaBean design patterns for interoperability. (This means
they are written so they all behave in a predictable way. IDEs can
be built to work with a set of JavaBean component in a standard
way as a JavaBean compliant IDE 'knows' how bean object
properties are declared and how the component can be used to
process events.

MVC Architecture

The Swing components make use of the Model-View-Controller
architecture that was originally developed with the invention of
the 'SmallTalk' programming language. The Swing 'widgets' have
a 'pluggable look-and-feel'. This means they can take on the
appearance of the visual controls that are native to the operating
platform, regardless of what platform the application is running on.
For example, an application can look like a Windows application,
even while running on an Apple computer or look like an application
running on an Intel 386 platform hosting Windows XP machine
though it is running Linux.

// Swing & AWT components are JavaBeans, that use SmallTalk's
// MVC design pattern design pattern and have a pluggable 'look & feel'


AWT Peer Based Components

Originally Java was shipped only 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 component from the MAC
toolkit. There were a number of problems that arose to get
these components to layout properly when applications were
ported to different platforms.

// AWT was 'peer-based' and as such had portability problems


Swing Peerless Components

The solution to resolve portability problems was to adopt a set
of 'peerless' components that all were drawn on the surface of
a single peer-based 'window' that acted as a base on which the
other components of the GUI would appear. The fact the GUI is
drawn superficially on one 'heavyweight' peer-based component
leads to the Swing components being described as 'lightweight'
and 'peerless'. These light-weight 'widgets' are written 100% in
Java and do not make any native API calls. Thus the Swing set
of components solved the portability problem.

More accurately, Swing lightweight components are drawn
on a single peer-based frame component making them easy
to scale on any platform.


Swing Packages extend AWT 

Swing components are an extension of AWT components rather
than a replacement for them. The Swing API was initially derived
from the Internet Foundation Classes, (IFCs) that were originally
developed by Netscape. After more work was done on them to
adapt them to Java, the framework was renamed 'Swing'. ( This
is unconfirmed, but it is said that one of the design team was fond
of jazz from the swing era and that is where the name came from.)

// IFC - Netscapes original Internet Foundation Classes


Java Extension Packages

Typically, when a new set of library classes are developed for
Java, they are introduced as an extension package. Sun tacks
an 'x' on the end of their '.java extension' packages. Inititially an
extension package is offered as a download which a developer
adds to his or her environment. If popular the package is often
added to the next JDK release.

// the 'x' in javax stands for extension

Swing, initially, was also one of these extension packages and
so came in the javax.swing package. ( There it remains to the
present! ) To 'wildcard' import the Swing components for use in
your application you can add the following import to the top of
your code.


Example   

import javax.swing.*;


While Swing defining many new event types, Swing controls
are based on and are backwards compatible with the event
model defined in AWT so a second typical import that is made
is as follows. 


Example   

import java.awt.event.*;


Swing also works with the Layout Managers provided in AWT.
Layout managers provide automatic layout strategies, setting
the physically layout of components that are added to a frame
according to a pre-ordained plan. We look at these later. For
now we note, this adds another typical import that 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.

Typical Swing Application Imports

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;




The Swing Packages



Finally to round things off, we list the various swing
packages
outlined in early JDK documentation.

Swing components make up the majority of the Java
Foundation Classes. The
Swing collection was originally
made up of the following 17 packages.

The Original Swing 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).
                                             The 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 non-editable 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 applications.


This is just a brief introduction which we pursue in depth in the next
class.



Self Test                           Self Test With Answers


1) The x in javax.* stands for

a) export
b) extension
c) access
d) extra
 

2) Which of the following imports is responsible for bringing in
   the common layout
managers like GridLayout?

a)  import.java.layouts.*;
b)  import javax. swing.*;
c)  import java.awt.event.*;
 
d)  import java.awt.*;
 

3) Given the following class declaration which of the following is
   not correct.

class X implements Y, Z{    }

a)  X  x = new X( );
b)  Y  y = new Y( );
c)   Z  z = new X( );
 

4) Which of the following statements is not correct regarding interfaces.

a) A class can implement several interfaces
b) A class can be declared to be the type of an interface it implements
c) A class that implements an interface must provide implementations
   for the methods of the interface.
d) A method can be defined in an interface with a method body

 

5) Which of the following statements is not correct?

a) Interfaces can be defined that contain no methods.
b) Interfaces can multiply inherit
c) Methods in interfaces are by default abstract and public
d) Interface constants are static and may have public or private access.
 

6) Which of the following statements are not correct?

a ) Inner classes defined inside methods can only access
    local methods that are marked final.
b) An inner class is stored in a file that has the name of the
    outer class and the inner class separated by a period sign.
c) Inner classes can be marked static.
d) Inner classes are referenced via an outer class object via the dot operator.


Exercise


1) Using the naming methods outlined in the note, create
three inner classes inside an outer class and printout a
variable defined in each to console.

2) Create an interface that defines two constant and two
methods. Use all capitals for the name of the constants. This
is a naming convention in Java. Have the class you built above
implement this interface and call the two methods. Design the
two methods to print to console the  two constants defined in
the interface.