SDSU CS 596 Java Programming
Fall Semester, 1998
JFC Basics
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 21-Dec-98

Contents of Doc 24, JFC Basics


Reference:


Graphic Java 1.2 Volume I: AWT 3 rd Edition, Geary, Chapters 1, 2 (pp. 20-22), 9 (pp237-269, 279-297), 10 (pp. 327-329), 11 (pp. 431- 439), 12 (pp. 483-484)


Listen Here!S-nov16 11mins, Q-nov19 6mins Doc 24, JFC Basics Slide # 2

Java Foundation Classes (JFC)


JFC Contains:

Abstract Window Toolkit (AWT)
Basic windowing components & structure
Swing Components
Lightweight components providing wide range of options
Java 2D
Full range of 2D operations
Accessibility Framework
Framework for making applications usable by people with impairments. Implementations of the framework to be provided by JavaSoft and third parties
Swing and Package names
Sun has changed its mind about the package name for the swing classes. The package name once was com.sun.java.swing. Some texts use the package name java.awt.swing. Now the Swing packages will be javax.swing in JDK 1.2. However, many texts were printed using the old names.

Java Media API
Sun's Java Media API includes Java 2D, Java 3D, Java Advanced Imaging, Java Media Framework, Java Shared Data Toolkit, Java Sound, Java Speech, and Java Telephony. However, only the Java 2D is part of the standard API in JDK 1.2. The others are or will be available as extensions to the JDK.

Listen Here!S-nov16 59secs, Q-nov19 3mins Doc 24, JFC Basics Slide # 3

Building GUIs - Abstract Window Toolkit (AWT)



Types of things in AWT

Components

Basic UI things like

Buttons, Checkboxes, Choices,
Lists, Menus, and Text Fields
Scrollbars and Labels

Containers

Contain components and containers

Window

LayoutManagers

Position items in window

Graphics

Drawing on the screen

Events


Listen Here!S-nov16 11mins, Q-nov19 4mins Doc 24, JFC Basics Slide # 4
Peers and Lightweight Components

Peers are native GUI components.

Some AWT classes use peers to display and manage a GUI component. For example, when you create a menu object in AWT, the JVM will create a menu using the platform's native menu code. The AWT menu object acts like a wrapper around the menu peer. Messages sent to the AWT menu object are eventually handled by the menu peer. The peer is the item that defines the look and behavior of the menu. This means that the behavior is defined by the platform.

Lightweight components
Use Java code to display and manage a GUI component.

A lightweight menu will not use the native peer. It would draw the rectangle around the menu, draw the menu text, etc. At some point, the lightweight menu will use some AWT component to perform some low-level graphic operation, which will use a peer to perform the operation. However, the Java code is used to define the look and behavior of the menu. A lightweight menu can have behavior that is not available on in the platform's native window system.
Look and feel is platform independent

Provides wide arrange of options for look and feel
Ports immediately to any Java supported system
May perform slower than a peer

Applets and Applications

The same GUI components used by applets and applications. Since applications are easier to implement and debug, we will start with applications.


Listen Here!S-nov16 2mins Doc 24, JFC Basics Slide # 5
Graphics 101

Window Coordinate System



Listen Here!S-nov16 3mins, Q-nov19 7mins Doc 24, JFC Basics Slide # 6
First Example
This example shows a simple application. Subclass Frame to get a window. The paint() method is called when window needs to be drawn. Do not call paint() directly. Becareful! You need to kill the process to quit this program.

import  java.awt.*;
class  HelloApplication  extends  Frame 
   {
   public  void  paint(  Graphics  display  )
      {
      int startX  =  30;
      int startY  =  40;
      display.drawString(  "Hello World", startX, startY  );
      }
   }
class Test
   {
   public  static  void  main( String  args[] )
      {
      HelloApplication  mainWindow = new  HelloApplication();
      int  width  =  150; // in pixels
      int  height  =  80;
      int left = 20; 
      int top = 40;
      mainWindow.setSize( width, height );
      mainWindow.setLocation( left, top);
      mainWindow.setTitle( "Hello" );
      mainWindow.show();
      }
   }
Output


Doc 24, JFC Basics Slide # 7
Hello Again
This example uses a Text label instead of drawing text.

import  java.awt.*;
class  HelloLabel  extends  Frame 
   {
   public HelloLabel( int left, int top, int width, int height, String title )
      {
      super( title );
      setSize( width, height );
      setLocation( left, top);
      Label hello = new Label( "Hello World", Label.CENTER);
      add( hello, BorderLayout.CENTER  );
      show();
      }
   }
class Test
   {
   public  static  void  main( String  args[] )
      {
      HelloLabel  mainWindow = new  HelloLabel( 20, 40, 150, 80, "Hi Dad");
      }
   }
Output


Listen Here!S-nov16 4mins Doc 24, JFC Basics Slide # 8

Java GUI Applications & NCD Terminals


There is problem running a Java GUI based application on the NCD terminals on campus. The problem is with the old version of the NCD software (3.x) running on the NCD terminals.

Reports are that version 5 of the NCD software fixes the problem. However, version 5 does not run on the older terminals in BAM and in E301. A few terminals in the library can run version 5.

This does not affect applets running in a browser, but does affect applets running in the appletviewer.

You must type

xstdcmap -all

at the shell prompt before you run a Java application that uses AWT and have it display on an NCD X-terminal in the BAM labs. This does not work with some window managers like fvwm.

Shift the Window Down

In most versions of the JDK the window coordinate system on the NCD is off by 10-30 pixels. You need add 10-30 pixels to the y coordinate system so that the top of the window is accessible.

Doc 24, JFC Basics Slide # 9

Event Model

Window Events

GUIs must handle events like mouse clicks, mouse movements, scrolling of a window.
JDK 1.0

Used inheritance-based event model for handling. Your classes override methods in AWT classes. These methods are called when an event occurs. Each component gets most events, so it has to determine if it should handle the event. While this mechanism still can be used, it should be avoided.

JDK 1.1 and Beyond

The inheritance-base event model was too slow and did not provide the control over events that applications needed. It is replaced with the delegation event model. This model uses listeners. Components register for events that they are interested in.

Listen Here!S-nov16 3mins, S-nov18 2mins, Q-nov19 3mins Doc 24, JFC Basics Slide # 10

Delegation Event Model


Event Sources

AWT items generate events (mouse down, mouse moved) that other AWT items must respond to.
Event Listeners

AWT items that must respond to events, need to "listen" the items that generate the events
Events

Event objects are created and sent to AWT listeners. The event objects contain information about the "event" that triggered the generation of the event object.


Listen Here!S-nov18 46secs, Q-nov19 1min Doc 24, JFC Basics Slide # 11
Example - Window EventsTypes of Events

windowActivated(WindowEvent)
Invoked when a window is activated.

windowClosed(WindowEvent)
Invoked when a window has been closed.

windowClosing(WindowEvent)
Invoked when a window is in the process of being closed.

windowDeactivated(WindowEvent)
Invoked when a window is de-activated.

windowDeiconified(WindowEvent)
Invoked when a window is de-iconified.

windowIconified(WindowEvent)
Invoked when a window is iconified.

windowOpened(WindowEvent)
Invoked when a window has been opened.


Doc 24, JFC Basics Slide # 12
WindowEventMethods
getWindow()
Returns the window where this event originated.
getComponent()
Returns the component where this event originated.
paramString()
consume()
getID()
Returns the event type.
getSource()
isConsumed()

Public Final Fields
WINDOW_ACTIVATED
The window activated event type.
WINDOW_CLOSED
The window closed event type.
WINDOW_CLOSING
The window closing event type.
WINDOW_DEACTIVATED
The window deactivated event type.
WINDOW_DEICONIFIED
The window deiconified event type.
WINDOW_FIRST
Marks the first integer id for the range of window event ids.
WINDOW_ICONIFIED
The window iconified event type.
WINDOW_LAST
Marks the last integer id for the range of window event ids.
WINDOW_OPENED
The window opened event type.


Listen Here!S-nov18 9mins, Q-nov19 6mins Doc 24, JFC Basics Slide # 13

Window Event Example

This example shows how to use a WindowListener to quit an application. Note that you cannot use System.exit(0) in an applet.

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.Frame;
import java.awt.Label;
class QuitableApplication1 extends  Frame 
   {
   public QuitableApplication1( int left, int top, int width, int height, String title )
      {
      super( title );
      setSize( width, height );
      setLocation( left, top);
      Label hello = new Label( "Hello World", Label.CENTER);
      add( hello, BorderLayout.CENTER  );
      addWindowListener( new QuitWindow( this ) );
      show();
      }
   }
class QuitWindow implements WindowListener
   {
   Frame myWindow;
   public QuitWindow( Frame aWindow )
      {
      myWindow = aWindow;
      }
   public void windowClosing(WindowEvent event) 
      {
      myWindow.dispose();
      System.exit(0);
      }
      
   public void windowActivated(WindowEvent event) {};
   public void windowClosed(WindowEvent event) {};
   public void windowDeactivated(WindowEvent event) {};
   public void windowDeiconified(WindowEvent event) {};
   public void windowIconified(WindowEvent event) {};
   public void windowOpened(WindowEvent event) {};
   }

Listen Here!S-nov18 4mins, Q-nov19 2mins Doc 24, JFC Basics Slide # 14
WindowAdapter
The WindowAdapter class implements, with null methods, all the methods in the WindowListener interface. By subclassing the WindowAdapter class, you can just implement the WindowListener methods you need.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.Frame;
import java.awt.Label;
class QuitableApplication2 extends  Frame 
   {
   public QuitableApplication2( int left, int top, int width, int height, String title )
      {
      super( title );
      setSize( width, height );
      setLocation( left, top);
      Label hello = new Label( "Hello World", Label.CENTER);
      add( hello, BorderLayout.CENTER  );
      addWindowListener( new QuitWindowAdapter( this ) );
      show();
      }
   }
class QuitWindowAdapter extends WindowAdapter
   {
   Frame myWindow;
   
   public QuitWindowAdapter( Frame aWindow )
      {
      myWindow = aWindow;
      }
      
   public void windowClosing( WindowEvent event )
      {
      myWindow.dispose();
      System.exit(0);
      }
   }

Listen Here!S-nov18 4mins, Q-nov19 3mins Doc 24, JFC Basics Slide # 15
Using Anonymous Classes
Using an anonymous class shortens the example. This use of anonymous classes is the main reason for adding them to the language.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.Frame;
import java.awt.Label;
class QuitableApplication3 extends  Frame 
   {
   public QuitableApplication3( int left, int top, int width, int height, String title )
      {
      super( title );
      setSize( width, height );
      setLocation( left, top);
      Label hello = new Label( "Hello World", Label.CENTER);
      add( hello, BorderLayout.CENTER  );
      addWindowListener( new WindowAdapter( ) {
               public void windowClosing( WindowEvent event )
                  {
                  dispose();
                  System.exit(0);
                  }
               }
             );
      show();
      }
   }

Listen Here!S-nov18 4mins, Q-nov19 3mins Doc 24, JFC Basics Slide # 16
Listening to Yourself
This example shows how use an adapter to have a class listen to itself. This allows the class to handle its own events.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.Frame;
import java.awt.Label;
class QuitableApplication4 extends  Frame 
   {
   public QuitableApplication4( int left, int top, int width, int height, String title )
      {
      super( title );
      setSize( width, height );
      setLocation( left, top);
      Label hello = new Label( "Hello World", Label.CENTER);
      add( hello, BorderLayout.CENTER );
      addWindowListener( new WindowAdapter( ) {
               public void windowClosing( WindowEvent event )
                  {
                  quit();
                  }
               }
             );
      show();
      }
   public void quit() 
      {
      dispose();
      System.exit( 0 );
      }
   }

Listen Here!S-nov18 53secs, Q-nov19 43secs Doc 24, JFC Basics Slide # 17

Overview of AWT Parts

Components

Components are basic UI things


Buttons, Checkboxes, Choices, Lists, Menus, and Text Fields

When a user activates one of these controls -- by clicking a button for example -- it posts generates an event.

Canvases and Text Areas

Ways of Getting User Input


Scrollbars and Labels

Listen Here!S-nov18 1min, Q-nov19 1min Doc 24, JFC Basics Slide # 18
Component Classes


Listen Here!S-nov18 2mins, Q-nov19 46secs Doc 24, JFC Basics Slide # 19
Containers: Windows and Panels

Containers contain components and containers

Window

Dialog, FileDialog, and Frame are subclasses of Window
Provide windows to contain components


Panels

Group components within an area of an existing window

Container Classes



Listen Here!S-nov18 3mins Doc 24, JFC Basics Slide # 20
Component

Background Color
void setBackground( Color)
Color getBackground()
Bounds
void setBounds( Rectangle )
void setBounds( int, int, int, int )
Rectangle getBounds()
Cursor
void setCursor( Cursor )
Cursor getCursor()
Drop Target
void setDropTarget(DropTarget)
DropTarget getDropTarget()
Enabled
void setEnabled( boolean)
boolean getEnabled()
Font
void setFont(Font )
Font getFont()
Foreground Color
void setForeground( Color )
Color getForeground()
Locale
void setLocale(Locale )
Locale getLocale()
Location
void setLocation( Point )
void setLocation( int, int )
Point getLocation()
Point getLocationOnScreen()
Name
void setName( String )
String getName()
Size
void setSize(Dimension )
Dimension getSize()
Visible
void setVisible(boolean)
boolean getVisible()

Deprecated Methods

The get/set convention was not strictly followed in JDK 1.0. In JDK 1.1, the convention was strictly enforced. Consequently, there are many deprecated methods in the Component class and its subclasses.

Listen Here!S-nov18 5mins, Q-nov19 4mins Doc 24, JFC Basics Slide # 21
Layouts

We need to specify where items will appear in a window. This has to be done on window that changes size and on different platforms: PC, Mac, Unix, PDA, toasters, and TVs. Layouts provide a flexible way to place items in a window without specifying coordinates.

AWT Layouts
BorderLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout

BorderLayout
Default layout for a frame
Divides area into named regions:

FlowLayout

Displays components left to right, top to bottom

Listen Here!S-nov18 7mins, S-nov18b 9mins, Q-nov19 6mins Doc 24, JFC Basics Slide # 22

Button Examples

We will use buttons to illustrate some basics of layouts, components, and events.

FlowLayout
This example creates a FlowLayout that aligns its components to the left. "new FlowLayout()" will create a FlowLayout that centers its components. Note how the buttons in the window "flow" as the window's shape is changed.

import java.awt.*;
class  FlowLayoutExample  extends Frame  {
   
   public FlowLayoutExample( int  width, int height ) {
      setTitle( "Flow Example" );
      setSize( width, height );
      setLayout( new FlowLayout( FlowLayout.LEFT) );
      
      for ( int label = 1; label < 10; label++ )
         add( new Button( String.valueOf( label ) ) );
      show();
   }
   public  static  void  main( String  args[] ) {
      new  FlowLayoutExample( 175, 100 );
   }
}
Output






Listen Here!S-nov18b 9mins, Q-nov19 8mins Doc 24, JFC Basics Slide # 23
BorderLayout
Since the BorderLayout is the default, we do not have to use the setLayout() method to specify the BorderLayout. It was done here just to insure that readers know that we are using the BorderLayout. Note how the layout deals the buttons as the window is resized.

import java.awt.*;

class  BorderLayoutExample  extends Frame  {
   
   public BorderLayoutExample( int  widthInPixels, 
                           int heightInPixels ) {
      setTitle( "BorderLayout Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new BorderLayout() );
      
      add( new Button( "North" ), BorderLayout.NORTH );
      add(  new Button( "Center" ), BorderLayout.CENTER );
      add(  new Button( "East" ), BorderLayout.EAST );
      add(  new Button( "West" ), BorderLayout.WEST );
      add(  new Button( "South" ), BorderLayout.SOUTH );
      show();
   }
   
   public  static  void  main( String  args[] ) {
      new  BorderLayoutExample( 175, 100 );
   }
}
Output





Listen Here!S-nov18b 9mins, Q-nov19 4mins Doc 24, JFC Basics Slide # 24

Button Events

Buttons support ActionListeners. When the mouse is pressed and released on a button, all listeners are send the actionPerformed() method. In this example we only need to know when the button was selected, so we do not use the ActionEvent.

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class  ButtonExample  extends Frame {
   Button red = new Button( "Red" );
   Button blue = new Button( "Blue" );
   
   public ButtonExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      add( red );
      add( blue );
      
      red.addActionListener( new ColorActionListener( Color.red) );
      blue.addActionListener( new ColorActionListener( Color.blue) );
      show();
   }
   public  static  void  main( String  args[] ){
      ButtonExample  window = new  ButtonExample(200, 50);
      }
   
   class ColorActionListener implements ActionListener {
      Color backgroundColor;
      
      public ColorActionListener( Color aColor ) {
         backgroundColor = aColor;
      }
      
      public void actionPerformed( ActionEvent event )  {
         setBackground( backgroundColor );
         repaint();      // Show effect of color change
      }
   }
}


Listen Here!S-nov18b 3mins, Q-nov19 33secs Doc 24, JFC Basics Slide # 25
Button ActionEvent
This example, which takes two slides, show how to use the ActionEvent.

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class  ActionEventDataExample  extends Frame
   {
   Button left = new Button( "Left" );
   Button right = new Button( "Right" );
   
   public ActionEventDataExample( int  widthInPixels, int heightInPixels )
      {
      setTitle( "Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      add( left );
      add( right );
      
      left.addActionListener( new ActionData( ) );
      right.addActionListener( new ActionData( ) );
      show();
      }
            
   public  static  void  main( String  args[] ){
      ActionEventDataExample  window = 
         new  ActionEventDataExample(200, 50);
      }

Listen Here!Q-nov19 9mins Doc 24, JFC Basics Slide # 26
Button ActionEvent Continued

   class ActionData implements ActionListener
      {
      public void actionPerformed( ActionEvent event ) 
         {
         String command = event.getActionCommand();
         int modifiers = event.getModifiers();
         String parameters = event.paramString();
         System.out.println( "Command " + command);
         System.out.println( "Parameters " + parameters);
         
         switch ( modifiers )
            {
            case ActionEvent.ALT_MASK: 
               System.out.println( "Alt Key was pressed");
               break;
            case ActionEvent.CTRL_MASK: 
               System.out.println( "Control Key was pressed");
               break;
            case ActionEvent.META_MASK: 
               System.out.println( "Meta Key was pressed");
               break;
            case ActionEvent.SHIFT_MASK: 
               System.out.println( "Shift Key was pressed");
               break;
            default:
               System.out.println( "No modifier keys were pressed");
            }
         }
      }
   }
Output



Listen Here!S-nov23 3mins Doc 24, JFC Basics Slide # 27
Identifying Buttons by Label - Just Say No
Button labels can change. While you may be tempted to identify which button was pressed by it name or label, avoid doing so. It is safer to use the name to the button. Safer still to use the button reference.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class BadExample extends Frame
   {
   Button red = new Button( "Red" );
   Button blue = new Button( "Blue" );
   
   public BadExample( int  widthInPixels, int heightInPixels )
      {
      setTitle( "Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      add( red );
      add( blue );
      
      red.addActionListener( new BadColorActionListener( ) );
      blue.addActionListener( new BadColorActionListener( ) );
      show();
      }
   public  static  void  main( String  args[] ){
      BadExample  window = new  BadExample(200, 50);
      }
   
   class BadColorActionListener implements ActionListener
      {
      public void actionPerformed( ActionEvent event ) 
         {
         String button = event.getActionCommand();
         if ( button.equals( "Red" ) )
            setBackground( Color.red );
         else if ( button.equals( "Blue" ) )
            setBackground( Color.blue );
         repaint();      // Show effect of color change
         }
      }
   }

Listen Here!S-nov23 2mins Doc 24, JFC Basics Slide # 28
Custom Buttons
We can create subclasses of Button, which will add functionality to the basic Button class.

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class CountButton extends Button implements ActionListener {
   int count = 0;
   
   public CountButton() {
      super( "0" );
      addActionListener( this );
   }
   
   public void actionPerformed( ActionEvent event )  {
      if (event.getSource() == this ) {
         count++;
         setLabel( String.valueOf( count ) );
      }
   }
}
class  SpecialButtonExample  extends Frame {
   public SpecialButtonExample( int  widthInPixels, int heightInPixels ) {
      setTitle( "Button Example" );
      setSize( widthInPixels, heightInPixels );
      setLayout( new FlowLayout() );
      add( new CountButton() );
      
      show();
   }
            
   public  static  void  main( String  args[] ){
      SpecialButtonExample  window = new  SpecialButtonExample(200, 50);
   }
}
Output (after a number of mouse clicks)

Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 16-Nov-98