You are on page 1of 373

SAP AG JA200 0-1

SAP AG 2003
JA200
THE BE8T THE BE8T THE BE8T THE BE8T- -- -RUN BU8NE88E8 RUN 8AP RUN BU8NE88E8 RUN 8AP RUN BU8NE88E8 RUN 8AP RUN BU8NE88E8 RUN 8AP
SAP AG 2003
JA200 JA200 JA200 JA200
Gui Kit



n Collection 32
n mySAPTechnology
n Material number: 50061312
SAP AG JA200 0-2
SAP AG 2003
Copyright 2003 SAP AG. All rights reserved.
No part of this publication may be reproduced or transmitted in
any form or for any purpose without
the express permission of SAP AG. The information contained
herein may be changed without prior notice.
All rights reserved.
Copyright



Comments on trademarks:
n Some software products marketed by SAP AG and its distributors contain proprietary software
components of other software vendors.
n Microsoft, WINDOWS, NT, EXCEL, Word, PowerPoint and SQL Server are registered
trademarks of Microsoft Corporation.
n IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390,
AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner,
WebSphere, Netfinity, Tivoli, Informix and Informix Dynamic ServerTM are trademarks of
IBM Corporation in USA and/or other countries.
n ORACLE is a registered trademark of ORACLE Corporation.
n UNIX, X/Open, OSF/1 and Motif are registered trademarks of the Open Group.
n Citrix, the Citrix logo, ICA, Program Neighborhood, MetaFrame, WinFrame,
VideoFrame, MultiWin and other Citrix product names referenced herein are trademarks of
Citrix Systems, Inc.
n HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C, World Wide
Web Consortium, Massachusetts Institute of Technology.
n JAVA is a registered trademark of Sun Microsystems, Inc.
n JAVASCRIPT is a registered trademark of Sun Microsystems, Inc., used under license for
technology invented and implemented by Netscape.
n MarketSet and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One.
n SAP, R/, mySAP, mySAP.com, xApps, xApp, and other SAP products and services mentioned
herein as well as their respective logos are trademarks or registered trademarks of SAP AG in
Germany and in several other countries all over the world. All other product and service names
mentioned are the trademarks of their respective companies.
SAP AG JA200 0-3
SAP AG 2003
Table of Contents
Preface
Unit 1 Introduction
Unit 2 AWT
Unit 3 Swing
Unit 4 SWT
Unit 5 Browser-Based GUI Development




SAP AG JA200 1-1
SAP AG 2003
Introduction
Contents:
l Course Model, Motivation
l Internationalization
l Internal Classes
l Observer Pattern



SAP AG JA200 1-2
SAP AG 2003
Course Overview Diagram
Introduction
Preface
AWT
Swing
Browser-Based GUI
Development
SWT



SAP AG JA200 1-3
SAP AG 2003
Course Model



n Course model:
The course "JA200 GuiKit" is based on the object model of SAP's Java course "JA100 StartupKit".
This slide shows the most important packages/classes.
n Basis model
The following packages make up the core of the object model:
Package com.sap.epf.ja100.app
The class CarControllApp represents the starting point of the application.
Package com.sap.epf.ja100.util
This package contains useful utility classes.
Package com.sap.epf.ja100.persist
These classes are responsible for input/output in files, database and so on.
Package com.sap.epf.ja100.model
Here data is stored in appropriate objects at runtime.
Package com.sap.epf.ja100.cmd
These classes control the access to the model's objects (business logic).




SAP AG JA200 1-4
SAP AG 2003
Based on the
basic model, you create
a graphical interface
using AWT and Swing.
Motivation



n Motivation
The course "JA200 GuiKit" will teach you how to create graphical interfaces using the classes of the
packages awt and swing in the JDK.
In so doing, you will replace the shell-based user interface from the course "JA100 StartupKit" with
relevant GUIs.

The basic model of JA100 is provided for you as a .jar file ("black box") so that you can concentrate
on the GUI programming.

SAP AG JA200 1-5
SAP AG 2003
Internationalization: Class Overview
Object
java.lang
<<abstract>>
Format MessageFormat
java.lang.text
<<abstract>>
NumberFormat
<<abstract>>
DateFormat
DecimalFormatSymbols
DateFormatSymbols
DecimalFormat
ChoiceFormat
SimpleDateFormat
java.util
Locale
<<abstract>>
ResourceBundle
PropertyResourceBundle
ListResourceBundle
Internationalization: Class Overview



n Uses:
Text in menus, buttons, windows, and so on
Formatting numbers, such as sums of money, date or time
Displaying addresses or telephone numbers
Graphics
Multimedia objects
Layout or colors
Multilingual messages
SAP AG JA200 1-6
SAP AG 2003
java.util.Locale
public locale (string language, string country, string variant)
Locale
Operating system
Java Virtual
Machine
default locale
Country (ISO 3166)
for example "CH" for
Switzerland
Language
(ISO - 639),
for example
"de"
for German
Variant (if necessary),
for example user
group
Locale.getDefault()
java.lang
Locale
java.util
Locale
Object
java.util.Locale



n Country and language-specific settings are encapsulated in the class java.util.Locale. The Java
Virtual Machine has a standard object of the class locale, which is filled with the values set in the
operating system. It can be read using Locale.getDefault().
n Using the getLanguage() method, the local language can then be queried as a two-character
code in accordance with ISO 639. Similarly, the getCountry() method returns the two-character
country code in accordance with ISO 3166. Additionally, it is also possible to pass your own variant
abbreviations with the locale object in the constructor, which can later be accessed using
Locale.getVariant().
SAP AG JA200 1-7
SAP AG 2003
ResourceBundle
Object
java.lang
<<abstract>>
ResourceBundle
java.util
ListResourceBundle
ResourceBundle
1 static ResourceBundle getBundle (String basisname,
Locale locale);
2 Object getObject (String key);
3 String getString (String key);
4 String[ ] getStringArray (String key);
PropertyResourceBundle
ResourceBundle



n To enable simpler translation of programs into various languages, you should store all country-
specific names, descriptions, or objects in general in specific files and classes. The JDK provides the
class java.util.ResourceBundle for this purpose. It makes use of the two subclasses
PropertyResourceBundle und ListResourceBundle.
n The class PropertyResourceBundle encapsulates all character strings that were read from specific
text files. However, since it is not just texts that can be country-specific, but also more complex
objects (such as graphics), these objects can also be grouped together using ListResourceBundle.
n Regardless of whether ResourceBundles are grouped using the class ListResourceBundle or using
"properties files", the country-specific packages are all loaded and used with the methods of the
superclass ResourceBundle.
n Methods
Line 1: Returns the subclass of ResourceBundle with the name basisname and the language variant
locale.
Line 2: Returns the object of the ResourceBundle with the key.
Line 3: Returns the character string of the ResourceBundle with the key.
Line 4: Returns the string array of the ResourceBundle with the key.
SAP AG JA200 1-8
SAP AG 2003
Implementing ResourceBundle
Option 1: Property Files
Create a text file in accordance with the naming convention (see
below)
Enter the parameters in the format: key name = value
Comment lines are marked with an asterisk (#)
dialog.add.truck=LKW hinzufgen
dialog.add.car=PKW hinzufgen
dialog.save=\u0020sichern

1 ResourceBundle bundle = ResourceBundle.getBundle(MyBundle);


2 System.out.println(Text:+bundle.getString(dialog.save));
Text: save
dialog.add.truck=add truck
dialog.add.car=add car
dialog.save=\u0020save

Text: sichern
MyBundle_de.properties MyBundle_en.properties



n Naming convention
basic class + "_" + language1 + "_" + country1 + "_" + variant1
basic class + "_" + language1 + "_" + country1
basic class + "_" + language1
Examples: MyResources_de_DE_bay, MyResources_de_CH, MyResources_fr_FR
n Blank characters
Blanks before and after the string in a property file are usually ignored. However, should you still
want precede a string in a property file with a blank, use the Unicode:
Line 1: The ResourceBundle is created.
Line 2: The value for the key "dialog.save" is output (with a preceding
blank).
SAP AG JA200 1-9
SAP AG 2003
Implementing ResourceBundle,
Option 2: Class ListResourceBundle
Derive your own class from ListResourceBundle
Name the class in accordance with the naming convention
Create the parameters as a two-dimensional array
Override the method public Object[][] getContents()
1 package com.sap.epf.ja100;
2 import java.util.*;
3 public class MyBundle_en_EN extends ListResourceBundle {
4 private Object[][] contents = {
5 { dialog.add.truck", Add truck },
6 { dialog.add.car", Add car },
7 { dialog.save", Save }
8 };
9 public Object[][] getContents() {
10 return contents;
11 }
12 }
13 ...
14 Locale currentLocale = new Locale("en","EN");
15 ResourceBundle bundle =
ResourceBundle.getBundle("com.sap.epf.ja100.MyBundle",
currentLocale);
16 System.out.println(bundle.getString("dialog.add.car"));



n The class ListResourceBundle is needed first and foremost because you can only store character
strings in "property files. Other, more complex objects, such as graphics data or similar, must be
made available using ListResourceBundles.
Line 1: To do so, derive your own class from ListResourceBundle.
Line 3: In your class, create an object array with the language-specific parameters
Line 8: Then override the getContents() method so that it returns a two-dimensional array of
objects consisting of key-value pairs.
Call:
Line 14: Create a locale instance.
Line 15: Create a ResourceBundle instance. You must specify the fully-qualified class name and the
locale object as the parameter.
SAP AG JA200 1-10
SAP AG 2003
Internal Classes 1
abstract class Vehicle {
class Tyre {
String producer;
float radius;
}
Tyre leftWheel= this.new Tyre();
Tyre rightWheel= this.new Tyre();
static void checkTyre(Vehicle vhcl) {
if (vhcl.spareTyre == null) {
vhcl.spareTyre= vhcl.new Tyre();
}
}
}
As well as constructors, methods, and
attributes there is an additional Java class
component as of JDK 1.1:
Internal Classes



n Internal Classes
Most Java classes are part of a special package (default: standard package). Classes that are defined
at package level are known as top level classes.
As of Java 1.1, it is possible to define internal classes. These classes:
- Are defined as a member of another class, within a statement block, or anonymously in an
expression
- Have a very limited task
n Name
Every internal class has its own .class file, which must be made available together with the top level
class.
The name of the internal class:
- Is linked with the name of the class that contains the internal class. It is assigned automatically
when the program is compiled.
- Is not visible outside its validity area, except for in a complete name specification.
SAP AG JA200 1-11
SAP AG 2003
Internal Classes 2
Internal class
Local class
Anonymous class
Static: Internal class|
interface
1
1
2
3
4
1 public class A {
2
3 public class InA {
4 ...
5 } // end of inner class InA
6
7 public void aMethod() {
8 public class InB {
9 ...
10 } // end of inner class InB
11 } // end of aMethod()
12
13 public Object a3rdMethod() {
14 return (new Object() {...});
15 }
16
17 public static class InD {
18 ...
19 } // end of inner class InB
20
21 } // end of outer class A



n Access
Access from outside can be restricted using the known modifiers. Conversely, you can also access
the attributes of the surrounding validity areas from the internal class. This includes both classes and
variables of surrounding classes as well as local variables of surrounding blocks.
SAP AG JA200 1-12
SAP AG 2003
Are declared at the uppermost level within the class body, parallel
to the attributes of a class
Are stored as separate byte-code files (for example, "A$InA.class")
Compiler
A.class
A.class
A$InA.class
A$InA.class
A.java
A.java
class A
\\ Attributes
\\ Methods
class InA
// Attributes
// Methods
1
1
1 public class A {
2 // attributes of class A
3 public class InA {
4 ...
5 } // end of inner class InA
6 // methods of class A
7 } // end of outer class A
Internal Classes 3



n An internal class is no different from an auxiliary class. Both classes are in the same source file,
which also contains the main file of the program.
However, since an internal class is defined in the main class itself, this gives rise to the following
advantages:
Internal classes are generally not visible to other classes. Therefore, no naming conflicts can arise.
Internal classes can access attributes and methods of top level classes, which they would not be
able to do as independent classes.
SAP AG JA200 1-13
SAP AG 2003
Are declared within a local statement block in the relevant method
of a class
Are stored as separate byte-code files (for example, "B$InB.class")
1 public class B {
2 // attributes of class B
3
4 public void aMethod() {
5 class InB {
6 ...
7 } // end of local class InB
8 } // end of aMethod()
9
10 class InB {
11 ...
12 } // end of inner class InB
13
14 } // end of outer class B B.class
B.class
B$InB.class
B$InB.class B.java
B.java
Compiler
B$1$InB.class
B$1$InB.class (local)
(inner)
(outer)
Local Classes
2
class B
\\ Attributes
\\ Methods
class InB
// Attributes
// Methods



n Internal classes can also be defined within a method of an outer class.
The internal class can then access any variable of this method (even parameters that are passed to the
method), provided the variable is defined as final.

However, classes that are defined within a method are not available outside the method.
SAP AG JA200 1-14
SAP AG 2003
Are declared within a local statement block in a method of a class and do not
have their own names
Are stored as separate byte-code files (for example, "C$1.class")
C.class
C.class
C$1.class
C$1.class
C$2.class
C$2.class
C$3.class
C$3.class
l An anonymous class is defined and
instantiated within a statement
Compiler
3
class C
\\ Attributes
\\ Methods
class InB
// Attributes
// Methods
C.java
C.java
1 public class C {
2 // attributes of class C
3
4 aMethod(new MyClass() {...});
5
6 public void adMethod( MyClass xy ) {
7 // do something
9 }
10
11 public Object a3rdMethod() {
12 return (new Object() {...});
13 }
14 } // end of outer class C
Anonymous Classes



n The above example shows the use of anonymous classes:
Line 4: A method (line 6) expects an object as a parameter. Here you can define and instantiate an
anonymous class.
Line 12: A method returns an object. It can be defined and instantiated as an anonymous class within
a single statement.
SAP AG JA200 1-15
SAP AG 2003
Internal classes defined as static automatically become top level
classes, that is they then lose the ability to access
attributes/methods and other internal classes of the outer class
Non-static internal classes cannot have any static attributes,
methods, or classes
Static: Internal Classes and Interfaces
Package xy
4
class A
\\ Attributes
\\ Methods
static class
InA
// Attributes
// Methods
class B
\\ Attributes
\\ Methods



n Internal classes defined as static can (like packages) also be used for structuring applications.
SAP AG JA200 1-16
SAP AG 2003
Advantages of Internal Classes
Internal classes are used intensively by the Java library in the
context of event controlling
Access from the outside can be restricted with the known modifiers (for
example, private or protected). An internal class can also be defined
as abstract.
As a result, internal classes are generally not visible to other classes.
Therefore, no naming conflicts can arise.
Internal classes can be used to hide source code sections and, for
example, make objects only available via an interface.
Internal classes can (like packages) also be used for structuring
applications.



n An internal class is no different from an auxiliary class. Both classes are in the same source file,
which also contains the main file of the program.
However, since an internal class is defined in the main class itself, this gives rise to the above
advantages.
SAP AG JA200 1-17
SAP AG 2003
l This pattern is used to create a relationship between an object, whose state
can change, and its observers, who are interested in the change of state.
The pattern consists of:
Event trigger
Defines methods with which observers are de/registered and can be
notified of any changes of state.
Interface (implemented by the observer)
Defines a method (for example, eventPerformed) that is called whenever
the state of the observed object changes.
Event listener, observer
Implements the above interface and hence the code that is required for
processing the change of state.
Registers itself with all objects, whose changes of state it is interested in.
Observer Pattern 1



n Observer pattern
With object-oriented programming, programs are split into many small, autonomous components.
However, as the number of objects increases, so do their communication requirements, and ensuring
the consistency of the data requires significant effort. The observer pattern describes how objects can
inform one another about changes of state.
You come across the observer pattern throughout the Java class library. It is most commonly used
for programming graphical interfaces.
SAP AG JA200 1-18
SAP AG 2003
Event listener
Attributes
Methods
Event trigger
Event trigger
l Provides methods with which listeners can be registered,
deregistered, and notified.
The listeners must implement a listener interface.
l Stores the references to the listeners in an internal list.
Register
Deregister
Event listener
Observer Pattern 2
Event trigger
Attributes
Methods
Event listener
Attributes
Methods
InterfaceIObserver
eventPerformed(Event ev)



n Event trigger
The object that wants to generate events (event trigger) must maintain a type of internal distribution
list. This is a list of all objects (listeners) that wish to be notified about changes of state and can and
want to receive event objects.
SAP AG JA200 1-19
SAP AG 2003
Event listener
Attributes
Methods
Event listener
Attributes
Methods
Event
l As soon as a specific state has been reached in the event trigger, an
event object is created and passed on to all registered listeners
l In so doing, the method defined in the listener interface is called
Event trigger
notifies
Event listener
InterfaceIObserver
eventPerformed(Event ev)
Observer Pattern 3
Event trigger
Attributes
Methods
EventX



n Event
If an event occurs in the event trigger, an event object is created. Using the methods defined in the
interface, this object is then passed on to all listener objects registered with the event trigger.
Using special methods of the relevant event class, the listener objects are now able to get information
about the type and origin of an event.
SAP AG JA200 1-20
SAP AG 2003
EventX
Event listener
Attributes
Methods
Event listener
Attributes
Methods
Event listeners
l Implement a listener interface
l Register themselves with the event trigger (or are registered)
l Are notified by the event trigger when an event occurs and process
the passed event object
notifies
Event listener Event trigger
Register
Deregister
InterfaceIObserver
eventPerformed(Event ev)
Observer Pattern 4
Event trigger
Attributes
Methods



n Event listener
All listener objects must implement a specially predefined interface (event interface). This enables
them to register with the object triggering the event.
The fact that all listener objects must implement the event interface ensures that they also contain all
event processing methods defined in the interface (general purpose of an interface).
SAP AG JA200 1-21
Project Settings


Unit: Introduction
Topic: Development Environment Settings

At the conclusion of these exercises, you will be able to:
Configure the development environment for the course JA200

0-1 Check that all directories and files necessary for the course are installed. To do so,
start Windows Explorer.
Select the Java course directory. Double-click the background program
qdCheck.bat. The following (or similar) should be displayed.

javacourse status: ok
jviewer status: ok
classpath. . . .: %classpath%;.;
coursepath. . . : C:\JavaCourse
sourcepath. . . : C:\JavaCourse\GuiKit
jviewerpath. . .: C:\JavaCourse\JViewer


0-2 Start Eclipse
In Windows Explorer, choose the directory <coursePath>. The Eclipse workbench
should then be started. If this is not the case, open the background file using an editor
and adjust the path specifications as necessary.

0-3 Create a new project file in Eclipse
In Windows Explorer, choose the directory <jviewerPath>. Double-click the
background program JViewer.bat.
In the directory tree, navigate to the point JA200 / Exercises / lab01 / 1. Have a look
at the graphics Getting started 1 and Getting started 2. Create a corresponding
project file in Eclipse.

Pay particular attention to the following points:
Step 3, project name: GuiKit
Step 4, output folder: GuiKit/bin
Step 5/6, additional libraries Select and add JA100.jar and JA200.jar.


SAP AG JA200 1-22
Introduction Exercises


Unit: Introduction
Topic: Observer Pattern
Optional Exercise

At the conclusion of this exercise, you will be able to:
Implement the observer pattern using dynamic data containers and
interfaces

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab01 + 1. Take a look at the graphics.
JVIEWER

Note:
The course JA200 GuiKit is based on a vehicle model that is discussed in detail in the
course JA100 StartUpKit. The classes of this course are available as .jar files and can
be used throughout the remainder of the exercises, provided you have made the relevant
project settings in the IDE.

Since you only use defined interfaces of JA100 classes in the exercises, you require no
knowledge of the internal structure and functions of these classes.

Observer Pattern
The observer pattern enables dynamic de/registration of observers with objects to be
observed (observable, trigger); the observers are informed of any change of state of the
observable objects.
The behavior of observer and observable is predefined in corresponding interfaces.

Observer: The concrete observer classes only implement callback methods that can be
called by the observable objects.

Observable: The concrete observable classes implement methods with which you can
register, deregister, and finally also inform any number of observers.



1-1 Open the package com.sap.epf.ja200.exc.lab01.

Here you will find the classes BusObjectEvent and Test.

Open the class Test. This starts the PersistManager from the package
com.sap.epf.ja100.persist. It is the PersistManagers task to load the
application data from Ascii files, create appropriate objects from it, and make these
objects available in relevant containers.
This is done with the following statements:
SAP AG JA200 1-23
PersistManager persistMgr = null;
try {
StaticData.setProperties (
com.sap.epf.ja200.app.CarControlApp.class,
"JA200.ini"
);
persistMgr = PersistManager.getInstance( null );
persistMgr.loadBusObjects();
} catch (Exception exc) {
System.out.println("Error loading Properties ");
System.out.println(exc.getMessage());
}
IPool iPool =
(IPool)persistMgr.getBusObjectPool("vehicle");
After loading the data and instantiating the objects, the data is available in so-called
pools and can be called from there, as described in the last line.

1-2 Change the Test class
It is your task to change the test class so that first the object references are copied from
the IPool iPool to another container. For every inserting operation into this second
container, an observer class (implemented by you) is to be informed.

1-3 First, define the observer interface IEventObserver
The interface is to be public and belong to the package
com.sap.epf.ja200.exc.lab01.
It should define the following method:
Modifier Return type Name/parameter list
public void eventPerformed( EventObject
event )

1-4 Now create the concrete observer class PoolObserver, which implements the
interface IEventObserver.
The class is to be public and belong to the package
com.sap.epf.ja200.exc.lab01.
Implement the method eventPerformed(...) required by the interface so that a message
is displayed on the console, for example:
System.out.println(Observer: notified);

1-4 Define the event trigger interface IEventTrigger.
The interface is to be public and belong to the package
com.sap.epf.ja200.exc.lab01.


SAP AG JA200 1-24
It should define the following methods:
Modifier Return type Name/parameter list
public void attachObserver(
IEventObserver observer )
public void detachObserver(
IEventObserver observer )
public void notifyObserver( EventObject
event )

1-5 The class to be observed is VehiclePool. Create this class in the package
com.sap.epf.ja200.exc.lab01.
Within the class, define the following attribute:
Modifier Type Name
private Vector observerPool
private Vector vehiclePool
Now make a standard constructor available and there assign each reference variable a
valid vector object:
All observer objects are de/registered in observerPool.
In vehiclePool, the copied references to vehicle objects are added.

1-6 Implement the interface IEventTrigger in the class VehiclePool.
Implement the methods provided by the interface so that:
attachObserver(...) inserts an observer in observerPool
detachObserver(...) removes an observer from observerPool
notifyObserver(...) notifies all observers that were registered in
observerPool.Use an iterator for this.

1-7 Provide a method addVehicleRow:

public void addVehicleRow( VehicleRow vehicleRow ) {
vehiclePool.add( vehicleRow );
notifyObserver(new BusObjectEvent(this,"row added"));
}
Note: The class BusObjectEvent is also provided. You can use it to pass on
information to all observers.
1-8 Change the class Test.
1. Insert code at the highlighted point in the main method:
2. First, create an instance of the class VehiclePool
3. Then create an instance of the class PoolObserver
4. Add the PoolObserver to the VehiclePool
5. Use the iterator iter to copy all objects from iPool to your container of the
type VehiclePool

1-9 Compile and test the application.

SAP AG JA200 1-25


Introduction Solutions


Unit: Introduction
Topic: Observer Pattern
1-1 Interface com.sap.epf.ja200.exc.lab01.IEventObserver

package com.sap.epf.ja100.exc.lab07;
import java.util.*;
public interface IEventObserver
extends EventListener {
public void eventPerformed( EventObject event );
}

1-2 Class com.sap.epf.ja200.exc.lab01.PoolObserver

package com.sap.epf.ja100.exc.lab07;
import java.util.*;

public class PoolObserver implements IEventObserver {

public void eventPerformed( EventObject event ) {
System.out.println("Observer: notified");
System.out.println("Action: "
+((BusObjectEvent)event).getAction() );
System.out.println("Source: "
+event.getSource() );
}
}


SAP AG JA200 1-26
1-3 Interface com.sap.epf.ja200.exc.lab01.IeventTrigger

package com.sap.epf.ja100.exc.lab07;
import java.util.*;

public interface IEventTrigger {
public void attachObserver(IEventObserver observer);
public void detachObserver(IEventObserver observer);
public void notifyObserver(EventObject event);
}

1-4 Class com.sap.epf.ja200.exc.lab01.VehiclePool

package com.sap.epf.ja100.exc.lab07;
import com.sap.epf.ja100.exc.lab04.Location;
import com.sap.epf.ja100.exc.lab05.*;
import java.util.*;

public class VehiclePool
implements IEventTrigger {

. . .
private Vector observerPool;

public void addVehicleRow(VehicleRow vehicleRow) {
vehiclePool.add( vehicleRow );
notifyObserver(
new BusObjectEvent( this, "row added") );
}
/**
* registriert die Observer
* adds new observer to internal list
*/
public void attachObserver(
IEventObserver observer ) {
observerPool.add( observer );
}

/**
* entfernt Observer
* removes observer from internal list
*/
public void detachObserver(
IEventObserver observer ) {
observerPool.remove( observer );
}

/**
* benachrichtigt alle registrierten Observer
* notifies all registered observers
*/
public void notifyObserver( EventObject event ) {
ListIterator iter = observerPool.listIterator();
while( iter.hasNext() ) {
IEventObserver observer =
SAP AG JA200 1-27
IEventObserver)iter.next();
observer.eventPerformed( event );
}
}

. . .
}
1-5 Class com.sap.epf.ja200.exc.lab01.Test

package com.sap.epf.ja100.exc.lab07;

public class Test {
public static void main(String[] args) {
VehiclePool vehiclePool =
VehiclePool.getInstance();
vehiclePool.attachObserver( new PoolObserver() );
...
}
}




SAP AG JA200 2-1
SAP AG 2003
Contents:
AWT
l Visual Components
n Window Classes
n Control Elements
n Layout Manager
n Menus (1)
l Event Handling
n Delegation Event Model
l Graphics Programming




SAP AG JA200 2-2
SAP AG 2003
Course Overview Diagram
Introduction
Preface
AWT
Swing
Browser-Based GUI Development
SWT




SAP AG JA200 2-3
SAP AG 2003
Unit Objectives
l Create a graphic user interface with the classes
of the package java.awt and its subpackages.
l Create programs for event handling.
At the conclusion of this unit, you will be able to:




SAP AG JA200 2-4
SAP AG 2003
With the AWT (abstract window toolkit), Java provides a collection of
platform-independent classes to defelop graphical user interfaces (GUI).
These are organized in the package java.awt and subpackages as
follows:
java.awt
Visual
components
- Window classes
- Control elements (controls)
- Layout of control elements
(layout manager)
- Menus
java.awt.color/font/
geom/image
Graphics
programming
java.awt.event
Event
control
User Interface Structure in the AWT



n Graphical Interfaces
Using the classes belonging to the packages java.awt and its subpackages, you can supply your
applications with graphical interfaces.
java.awt: Classes for different window types, control elements (controls), layout of
control elements (layout manager), design and control of menus, manipulation of colors, fonts, and
graphical content (lines, characters, and so on).
java.awt.image: Screen processing, that is, processing of screen data in binary formats, such as .gif
or .jpg.
java.awt.event: Message processing


SAP AG JA200 2-5
SAP AG 2003
Visual Components
java.awt
<<abstract>>
Component
<<abstract>>
Container
Panel
Frame
ScrollPane
Window Dialog FileDialog
Button
Canvas
Checkbox
Choice
List
Label
Scrollbar
TextComponent
TextArea
TextField
MenuComponent MenuBar
MenuItem
CheckboxMenu
Item
Menu PopupMenu
Font
<<Interface>>
MenuContainer
<<Interface>>
MenuContainer
<<Interface>>
ItemSelectable
<<Interface>>
Adjustable



n Layout Elements of the AWT

In Java, all visually displayable elements are derived from Basis classes that provide the necessary
functions for the various control elements.

The Basis class of the AWT is Component. Since each element of a GUI represents a component, it
is derived from Component (exception: classes for setting up menus are subclasses of
MenuComponent).

SAP AG JA200 2-6
SAP AG 2003
Window Classes
<<abstract>>
Component
<<abstract>>
Container
Panel
Frame
ScrollPane
Window Dialog FileDialog
Applet
java.awt
<<Interface>>
MenuContainer
<<Interface>>
MenuContainer



n Window Classes
The task of the abstract class Component is to represent a program element that has a size and
position, and is also able to transmit a large number of events and react to them.
The Container class is required in order to be able to include other components within a component.
For this purpose, it provides methods in order to add/remove components.
Together with the LayoutManager classes, it is also responsible for positioning and aligning
components.
The simplest class of all is Panel. It is primarily used to nest containers in order to influence the
layout of the components.
A direct subclass of Panel is the Applet class, which is important for the development of applets. It
enhances the functions of the Panel class to include methods that are important for executing applets.
The Window class abstracts a top-level window without frame, title bar, or menu. It is suitable for
applications that paint their frame elements themselves or require full control over the entire
window.
The Frame class represents a top-level window with frame, title bar, and optional menu. It contains
typical functions such as enlarging, reducing, changing the mouse cursor, and so on. Dialog is
another class derived from Window. It implements modal or non-modal dialogs.

SAP AG JA200 2-7
SAP AG 2003
Component
Object
java.lang
<<abstract>>
Component
java. awt
<<abstract>>
Container
List ScrollBar TextComponent
Button Canvas CheckBox
Choice
Label
The abstract class Component is the superclass for all
GUI elements in AWT.
Component encapsulates methods into the following functions:
Event control
Representation of the component on the screen
Basic functions for menu components
Focus control
Many of the methods are deprecated, that is, they should no
longer be used. Please heed this note.



n Component
Component groups together all the common attributes and methods of user interface components.

All the control elements of the AWT are derived from Component, that is, each subclass can
directly implement the attributes and method inherited from Component.

You can never instantiate Component directly. Instead you can:
- Use one of the other derivations (except for Container)
- Use a derivation of Component yourself
n Events
ComponentEvent, FocusEvent, KeyEvent, MouseEvent

SAP AG JA200 2-8
SAP AG 2003
Component: Attributes and Methods (1)
1 Rectangle getBounds( );
void setBounds(Rectangle r);
2 Point getLocation( );
void setLocation(Point p);
3 Point getLocationOnScreen( );
void setLocationOnScreen(Point p);
4 Dimension getMinimumSize/MaximumSize( );
void setMinimumSize/MaximumSize(Dimension d);
5 Dimension getSize( );
void setSize(Dimension d);
6 void resize( );
7 Font getFont( );
void setFont (Font f);
Component



n Methods
Line 1: Returns/sets the measurements and position of the control in the form of the Rectangle class.
Line 2: Returns/sets the position of the component relative to the outer component.
Line 3: Returns/sets the absolute position of the component on the screen.
Line 4: Returns/sets the minimum/maximum possible size of the component.
Line 5: Returns/sets the size of the component. There are two different set methods.
Line 6: Returns/sets the size of the component.
Line 7: Returns/sets the currently set font.

SAP AG JA200 2-9
SAP AG 2003
Component: Attributes and Methods (2)
1 FontMetrics getFontMetrics( );
void setFontMetrics(FontMetrics fm);
2 Color getForeground( );
void setForeground(Color c);
3 boolean getEnabled( );
void setEnabled (boolean b);
4 boolean getVisible( );
void setVisible(boolean b);
5 void paint (Graphics g);
6 void paintAll(Graphics g);
7 void repaint( );
8 void repaint(long tm);
9 void repaint (int x, int y, int width, int height);
10 void repaint(long tm, int x, int y, int width, int
height);
Component



n Methods

Line 1: Returns/sets an object that determines the font measurements.
Line 2: Returns/sets the foreground color. Usage depends on the class derived from Component.
Line 3: If Enabled is false, Control is blocked for inputs.
Line 4: Returns/sets whether the component is visible.
Line 5: Function used to (re-)paint Control. You use paint only if you wish to write your
own Control. For this purpose, you make a derivation from Component and
overwrite the paint method.
Line 6: paintAll additionally calls the paint method of all subcomponents.
Lines 7-10: Using repaint, you can have a component repaint itself.
For methods 9 and 10 you can specify a subarea that is repainted while the rest remains the same.
The argument tm in methods 8 and 10 specifies in how many milliseconds the repainting is to take
place.

SAP AG JA200 2-10
SAP AG 2003
Container
<<abstract>>
Component Panel
java. awt
ScrollPane Window
<<abstract>>
Container
The Container class is the superclass for all graphically displayable
classes in the AWT that contain other objects (components) at
runtime.
Container defines a series of methods to create, list, or reference new
controls, or to remove them from the Container.
Container is derived from Component.



n Container
The most important subclass of Component is the Container class. It is the starting point for all
components that have the property of being able to contain components themselves (for example, all
window classes, classes Applet and Panel).
One of the most important features of containers is that they not only can contain components
themselves, but that they can also be part of other containers.
It is possible to assign different layout procedures to the containers (->layout manager) . Therefore,
because of this nesting function, flexible layout of the GUI is possible, irrespective of the actual
application platform.

n Constructors
Container(): Creates a new container.

n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent

SAP AG JA200 2-11
SAP AG 2003
Container: Method Attributes
1 Component[ ] getComponents( );
2 int getComponentCount( );
3 Component getComponent(int n);
4 Component getComponentAt(int x, int y);
Component getComponentAt(Point p);
5 Component findComponentAt(int x, int y);
Component findComponentAt(Point p);
6 void add(Component comp);
void add(Component comp, int index);
7 void remove(Component comp);
void remove(int index);
8 void removeAll( );
Container



n Methods
Line 1: Returns/sets the references for the components contained in this container as an array.
Line 2: Returns the number of controls contained in this container.
Line 3: Returns the nth contained component.
Line 4: Using the getComponentAt methods, you can determine which components
are currently at the coordinate (x,y). If several components overlap, the uppermost
(visible) component is returned in each case.
Line 5: The find methods differ from the get methods in that, when there is a container at the
position
concerned, they search through this container for subcomponents. The get methods, on the
other hand, return the container.
Line 6: Using the add methods, you add a component to the container. The method
with int index adds the components to the position index in the array.
There are three further add methods. These all work specifically with the LayoutManager
methods. However, since this will not be discussed in detail during the course because of its
minimal use, the other add methods will not be discussed further either.
Lines 7-8: Using the remove methods, you can remove a component from a container.
The remove-all method removes all the subcomponents.

SAP AG JA200 2-12
SAP AG 2003
Panel
<<abstract>>
Container
java. awt
Panel
The Panel class is a container class for the organization of
control elements ("paint area").
The panel can itself be a part of another container object.
Panel is derived from Container.



n Panel
Within the AWT class hierarchy, a panel represents the simplest container class. Since it inherits all
attributes and methods from Container (and Component), it provides options to include further
components and align them on the screen.
n Constructors
Panel(): Creates a new panel using the standard Layout Manager.
Panel(LayoutManager layout): Creates a new panel with the passed Layout Manager.
We will explain the Layout Manager later on.

n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent

SAP AG JA200 2-13
SAP AG 2003
ScrollPane
<<abstract>>
Container
java. awt
ScrollPane
Diagram: ScrollPane with buttons
The ScrollPane class is a container class that contains only one
single component and provides scroll bars to view them.
ScrollPane is able to manage a virtual output area that is larger
than the area available on the screen.
ScrollPane is derived from Container.



n ScrollPane
ScrollPane has been introduced with version 1.1 of the JDK. ScrollPane is similar in function to
Panel. The differences compared to Panel are as follows:
ScrollPane can include exactly one dialog element.
ScrollPane does not require an explicit layout manager.
ScrollPane can manage a virtual output area that is larger than the area on the screen.
n Constructors
ScrollPane(): Creates a new ScrollPane. Scrollbars are displayed as required.
ScrollPane(int scrollbarDisplayPolicy): Creates a new ScrollPane. Here the parameter
ScrollbarDisplayPolicy defines the strategy for displaying the scrollbars:
ScrollPane.SCROLLBARS_AS_NEEDED Display only if required
ScrollPane.SCROLLBARS_ALWAYS Display always
ScrollPane.SCROLLBARS_NEVER Never display, segment can be moved by the program
only
n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent

SAP AG JA200 2-14
SAP AG 2003
Scrollpane: Attributes and Methods
1 void setSize(Dimension d);
void setSize(int width, int height);
2 Dimension getPreferredSize( );
3 void setUnitIncrement(int i);
4 Adjustable getHAdjustable( );
5 public Adjustable getVAdjustable( );
6 public Dimension getViewPortSize( );
7 public void setScrollPosition(int x, int y);
ScrollPane



n Methods
Line 1: Defines the visible size (Viewport) of the ScrollPane.
Line 2: Using this method, you define the virtual size of the element that you have inserted within
the ScrollPane using add().
.
Line 3: Sets the increment for the scrollbars.
Lines 4/5: Using getHAdjustable, you acquire an object that enables access to the
horizontal scrollbar (getVAdjustable() for the virtual scrollbar). Using the
adjustable interface, you can access the scrollbar.
Line 6: Returns the current size of the viewport.
Line 7: Moves the ScrollPane. The passed values must be between 0.0 and the corresponding
maximum size of the virtual output area - viewport size.
n Create ScrollPane:
1. Call constructor ScrollPane myScr= new ScrollPane();
2. Create component using add() myScr.add(<Element>);
3. Set visible size (viewport) myScr.setSize(100,200);
4. If necessary, set increment myScr.setUnitIncrement(20);
5. If necessary, set virtual size public Dimension getPreferredSize()
(in <Element>) return new Dimension(500,700);}

SAP AG JA200 2-15
SAP AG 2003
Window
<<abstract>>
Container
java. awt
Window Frame Dialog
The Window class represents a simple window without a
frame, a title bar, and menu.
Window requires either an object of the Frame class, an
object of the Dialog class, or another Window object as
"parent".
Window is derived from Container.



n The Window class represents a simple window without a frame, a title bar, and so on. Window was
used prior to JDK 1.1, for example, to implement pop-up menus (as of JDK 1.1, you now have
PopUpMenu for this purpose).
Normally you work with one of the classes Frame or Dialog derived from Window.

n Constructors
The constructors expect, as parameter, an object of the classes Frame, Dialog, or Window. This
object is thus a "parent" object of Window.
Window(Frame owner): Creates a new, invisible window with the specified frame as "parent" object.
Window(Frame owner): Creates a new, invisible window with the specified frame as "parent" object.
Window(Window owner,GraphicsConfiguration gc): Creates a new, invisible window with the
specified frame as "parent" object and a GraphicsConfiguration for a particular output device.
n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent, WindowEvent

SAP AG JA200 2-16
SAP AG 2003
Dialog
<<abstract>>
Container
java. awt
Window Dialog
Dialog creates the Basis class for modal dialog screens.
Diagram: Dialog
FileDialog
A modal dialog must always be derived from the Basis
class Dialog.
Dialog is derived from Window.



n Constructors
Dialog(Dialog owner): Creates a non-modal dialog (invisible at first) with an empty title and the
specified dialog as "parent" object.
Dialog(Dialog owner,String title): Creates a non-modal dialog (invisible at first) with the specified
title and the specified dialog as "parent" object.
Dialog(Dialog owner,String title): Creates a non-modal dialog (invisible at first) with the specified
title and the specified dialog as "parent" object.

n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent, WindowEvent

SAP AG JA200 2-17
SAP AG 2003
FileDialog
<<abstract>>
Container
java. awt
The FileDialog class is a pre-defined class for Open File /
Save File dialogs.
FileDialog is derived from dialog.
Diagram: FileDialog
FileDialog Dialog Window



n FileDialog
Objects of the FileDialog class represent predefined dialog fields for the commands File/open and
File/save

n Constructors
FileDialog(Frame parent): Creates a file dialog to load a file.
FileDialog(Frame parent,String title): Creates a file dialog with the specified title to load a file.
FileDialog(Frame parent,String title): Creates a file dialog with the specified title to load or save a
file.

SAP AG JA200 2-18
SAP AG 2003
Frame
<<abstract>>
Container
java. awt
Window Frame
The Frame class displays a window with frame and title bar.
Diagram: Frame



n Frame
The objects of the Frame classs represent independent, freely movable windows with frame, title bar,
and, if necessary, menus.

n Constructors
Frame(): Creates a new Frame instance that is invisible at first.
Frame(GraphicsConfiguration gc): Creates a new Frame instance with the specified
GraphicsConfiguration for a particular output device. The instance is invisible at first.
Frame(String title): Creates a new Frame instance with the specified title.
Frame(String title,GraphicsConfiguration gc): Creates a new Frame instance with the specified title
and the specified GraphicsConfiguration.
n Events
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent, WindowEvent

SAP AG JA200 2-19
SAP AG 2003
Setting Up Window Elements
1 String getTitle( );
void setTitle(String t);
2 void setIconImage(Image i);
3 void setCursor(Cursor c);
4 void set Background/Foreground(Color c);
5 void setFont(Font f);
6 void setSize(int width, int height);
void setSize(Dimension d);
7 void setBounds(int x, int y,int width,int height);
void setBounds(Rectangle r);
8 void setLocation(int x, int y);
void setLocation(Point p);
Frame



n Methods
Line 1: Sets/returns the window title (Frame, Dialog)
Line 2: Sets a window icon (Frame).
Line 3: Method from the Component class to be able to specify a cursor object to display a
mouse pointer.
The Cursor class:
The Cursor classs contains a constructor that expects an integer constant as single
argument to be able to choose the required cursor from the list of predefined cursor
types, for example:
Cursor.CROSSHAIR_CURSOR ->Crosshair
Cursor.DEFAULT_CURSOR ->Standard arrow
Cursor.MOVE_CURSOR ->Quadruple arrow
Cursor.WAIT_CURSOR ->Hourglass
Line 4: Sets the foreground and background colors (Component).
Line 5: For setting a standard font (container) of a window.
Line 6: Changes the size of the window to the value (width, height) or dimension
Line 7: Combines the functions setSize() and setLocation(), and positions a window of the
size (width,height) at the position (x,y).
Line 8: Moves the left upper corner to the screen position (x,y).

SAP AG JA200 2-20
SAP AG 2003
Control Elements
java.awt
CheckboxGroup
<<abstract>>
Component
<<Interface>>
MenuContainer
Button
Canvas
Checkbox
Choice
List
Label
Scrollbar
TextComponent
<<Interface>>
ItemSelectable
<<Interface>>
Adjustable
TextField
TextArea




SAP AG JA200 2-21
SAP AG 2003
Button
<<abstract>>
Component
java. awt
Button
The Button class displays a labeled pushbutton that can be
used to trigger actions when pressed by the user.
Button is derived from Component.
Diagram: Frame with Button



n Constructors
Button(): Creates a button without a label.
Button(String label): Creates a button with the specified label.

SAP AG JA200 2-22
SAP AG 2003
The Canvas class is a simple, rectangular area for painting
and can be used as the superclass for self-defined
components.
Canvas
<<abstract>>
Component
java. awt
Canvas
Diagram: Frame with Canvas
Canvas is derived from Component.



n Canvas
To use the options available for Canvas in your applications, you must define your own classes and
derive these from Canvas. Here you override the paint() method to display your outputs in the
canvas.
The appearance is defined for almost all components; therefore, the paint method should not
be overridden and the repaint method should not be called.
Only if you have components of the Canvas type, do you need to explicitly specify using the
paint method which graphical elements are to be represented. For this purpose, you define a
subclass of the class Canvas and override the paint method in it.
The paint method works with an object of the Graphics type and has the following setup:
public void paint (Graphics g) {
g.setColor (...);
g.draw... (...);
g.fill... (...);
}
n Constructors
Canvas(): Creates a new canvas.
Canvas(GraphicsConfiguration config): Creates a new canvas with the specified
GraphicsConfiguration.

SAP AG JA200 2-23
SAP AG 2003
Checkbox
<<abstract>>
Component
java. awt
Checkbox
The Checkbox represents a control element that has a
status variable that can be switched between the values
true or false.
Diagram: Frame with Checkbox
Checkbox is derived from Component.



n Checkbox
A checkbox contains a state variable that can be switched between the values true and false. The
current state is shown by a checkmark or a cross in the checkbox.
n Constructors
Checkbox(): Creates a checkbox without a description
Checkbox(String label): Creates a checkbox with the specified description.
Checkbox(String label,boolean state): Creates a checkbox with the specified description and the
specified state.
Checkbox(String label,boolean state,CheckboxGroup group): Creates a checkbox with the specified
description and the specified status in the specified CheckboxGroup.
Checkbox(String label,boolean state,CheckboxGroup group): Creates a checkbox with the specified
description and the specified state in the specified CheckboxGroup.
n Methods
In each case, a get and a set method for the attributes String Label and boolean State.

SAP AG JA200 2-24
SAP AG 2003
CheckboxGroup
Object
java.lang java. awt
CheckboxGroup
Diagram: Frame with CheckBoxGroup
A CheckboxGroup is nothing other than a set of Checkbox
objects that hold a reference to the same CheckboxGroup
object.
If you choose a checkbox, its internal status changes to
true and the status of the others changes to false.
Checkbox is derived from Object.



n CheckboxGroup
Unlike the situation with a standard Checkbox, there are only 2 constructors left available to which
an object of the class CheckboxGroup is passed.
The task of the CheckboxGroup is to define the group effect and the switching logic.
n Constructors (CheckboxGroup)
CheckboxGroup(): Creates a new CheckboxGroup instance.

n Constructors (Checkbox)
Checkbox(String label,boolean state,CheckboxGroup group): Creates a checkbox with the specified
description and the specified state in the specified CheckboxGroup.
Checkbox(String label,CheckboxGroup group,boolean state): Creates a checkbox with the specified
description and the specified state in the specified CheckboxGroup.

SAP AG JA200 2-25
SAP AG 2003
Checkbox/CheckboxGroup: Attributes and
Methods
1 Checkbox getSelectedCheckbox( );
2 void setSelectedCheckbox(Checkbox box);
CheckboxGroup
1 void setState(boolean state);
2 void setCheckboxGroup(CheckboxGroup cbg);
3 CheckboxGroup get CheckboxGroup( );
Checkbox



n Behavior of different methods in connection with a checkbox group
CheckboxGroup
Line 1: Returns the checkbox that is true.
Line 2: So that a checkbox in a Checkboxgroup is activated, it must be passed as a parameter.
Checkbox
Line 1: Works only with parameter true; however, the states of the other checkboxes in the group
are set to false.
Line 2: Can subsequently change the assignment of the checkboxes to a checkbox group.
Line 3: The object returned when you call this method can be used to access a selected element of
the checkbox group - with the help of the following methods.
n Events
ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent
The individual checkboxes of a checkbox group return, among other things, an item event -
whenever a checkbox has been activated by the user.

SAP AG JA200 2-26
SAP AG 2003
Choice
<<abstract>>
Component
java. awt
Choice
Diagram: Frame with Choice
Java
C++
Delphi
Smalltalk
The Choice class represents an expandable text field. You
can choose its content from a list preset by the program.
Choice is derived from Component.



n Choice
Dialog elements of the type Choice correspond to the standard drop-down listboxes under MS
Windows.
n Constructors
Choice(): Creates a selection menu.
n Methods
void addItem(String item): Each call attaches the passed element to the end of the list (no automatic
sorting!).
int getSelectedIndex(): Returns the index of the selected element so that, by passing it to String
getItem(int n), the respective element is used.

Alternatively, you can call the method String getSelectedItem(); in order to get the element directly
(without index).
int getItemCount(): Returns the number of elements that are currently in the list.

On the program side, you can use the following methods:void select(int idx)/void select(String
value): In this way, you can have an element selected either via the index or by searching for the
specified value.

SAP AG JA200 2-27
SAP AG 2003
Label
<<abstract>>
Component
java. awt
Label
Diagram: Frame with Label
The Label class serves for labelling dialog boxes.
Label contains one line of text that can be displayed and
also changed by the program.
Label is derived from Component.



n Constructors
Label(): Creates a label without a name.
Label(String text): Creates a label with the specified labeling (left-aligned).
Label(String text, int align):Creates a label with the specified labeling and the specified alignment.

If a parameter of the type String is passed, this is used as label.
The align parameter determines the alignment. Here you can pass the constants Label.LEFT,
Label.RIGHT, Label.CENTER to the label.

n Methods
void setText(String txt)/String getText(): Allows access to the text.
void setAlignment(int i)/int getAlignment(): Allows access to the text alignment.

SAP AG JA200 2-28
SAP AG 2003
List
<<abstract>>
Component
java. awt
List
Diagram: Frame with List(box)
The List class is a list-type display of values from which the
user can choose one or several.
An element of the List class is always visible in full size on
the screen.
List is derived from Component.



n Constructors
List(): Creates a new selection list.
List(int rows): Creates a new selection list with the specified number of visible lines.
List(int rows,boolean multipleMode): Creates a new selection list with the specified number of
visible lines and parameters for multiple selection.
The parameter-free constructor creates an empty list, the size of which is defined by the Layout
Manager. The rows parameter determines the number of displayed lines (there can be more lines in
the listbox than displayed). The multipleMode parameter specifies whether multiple selection is
allowed (true) or not (false).

SAP AG JA200 2-29
SAP AG 2003
List: Attributes and Methods
1 void add(String item);
2 int[ ] getSelectedIndexes( );
3 String[ ] getSelectedItems( );
4 void select(int index);
5 void deselect(int index);
6 void remove(String item);
7 void remove(int index);
8 void replaceItem(String newValue, int index);
List



n Methods
The List class provides almost the same functions as Choice.
Line 1: Each call attaches the higher-level element to the end of the list (no automatic sorting!).
Line 2: If you have multiple selection: returns an array with index positions of the selected elements.
Line 3: Returns a list of the selected values.

In the program you can use the following methods:
Lines 4/5: You can have individual elements selected/deselected.

In contrast to Choice, you have the following methods at your disposal:
Line 6: Deletes the element item.
Line 7: Deletes the element at the position idx.
Line 8: Replaces the element at the position idx by the text newValue.

SAP AG JA200 2-30
SAP AG 2003
Scrollbar
<<abstract>>
Component
java. awt
Scrollbar
Diagram: Frame with text field and scrollbars
A scrollbar is a movable bar that you can use to display
and enter a value from a predefined value range.
You can align the bar either horizontally or vertically. The
bar contains a slide that can be changed in size.
Scrollbar is derived from Component.



n Constructors
Scrollbar(): Creates a new vertical scrollbar.
Scrollbar(int orientation): Creates a new scrollbar with the specified orientation.
Scrollbar(int orientation,int value,int visible,int minimum,int maximum): Creates a new scrollbar
with the specified orientation, an initial value, page size, and minimum as well as maximum value.
The orientation parameter determines the orientation of the scrollbar using the constants
Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
n Methods
The methods of the Scrollbar class allow access to the scrollbar attributes. Most of these are defined
in the Adjustable interface, which is implemented by the Scrollbar class.
int getValue()/void setValue(int i):
Access the current value of the respective scrolbar.
int getMinimum/Maximum()/void setMinimum/Maximum():
Access the limits of the value range.
int get UnitIncrement/BlockIncrement()/void setUnitIncrement/ BlockIncrement(): Access the
parameters that define how much the value is to be changed when you click on the arrow button or
on the area between the scrollbar and the arrow button.

SAP AG JA200 2-31
SAP AG 2003
The TextComponent class is the parent class for the
classes TextArea and TextField. In this function it
combines attributes and methods that are used by these
subclasses.
TextComponent is derived from Component.
TextComponent
<<abstract>>
Component
java. awt
TextField TextComponent TextArea



n Methods
void setCaretPosition(int i): Sets the position of the cursor in the text.
int getCaretPosition(): Returns the position of the cursor in the text.
String getSelectedText(): Returns the currently selected text.
void setText(String txt): Sets the input text.
String getText(): Returns the input text.
void setSelectionStart/-End(int i):Defines the current selection area through start/end position.
int getSelectionStart/-End(): Returns the start or end point of the current selection area.
void setEditable(boolean b): Determines whether the control can be edited or is blocked.
boolean getEditable(): Returns whether the control can be edited or is blocked.
boolean select(int start,int end)/ boolean selectAll(): Selects the specified/total text segment.

SAP AG JA200 2-32
SAP AG 2003
TextArea
<<abstract>>
Component
java. awt
TextComponent TextArea
Using the TextArea class you can create multiline text
fields that you can additionally scroll horizontally and
vertically.
TextArea is derived from TextComponent.
Diagram: Frame with TextArea



n Constructors
TextArea() : Creates a new text area.
TextArea(int rows, int columns): Creates a new text area with the specified number of lines and
columns.
TextArea(String text): Creates a new text area with the specified text.
TextArea(String text,int rows,int columns): Creates a new text area with the specitfied text and the
number of lines and columns.
TextArea(String text,int rows,int columns,int scrollbars): Creates a new text area with the specified
text and the specified number of lines and columns, as well as the visibility of the scrollbar.
The scroll parameter contains one of the constants SCROLLBARS_BOTH,
SCROLLBARS_VERTICAL_ONLY, SCROLLBARS_HORIZONTALLY_ONLY, and
SCROLLBARS_NONE. In this way, you can define the layout of the text area with scrollbars.
n Methods
void insert(String str,int pos): Inserts the string str at the position pos.
void append(String str): Appends the string str to the existing text.
void replaceRange(String str,int start,int end): Replaces the text between start and end by str.
n Events
ComponentEvent, FocusEvent, KeyEvent, MouseEvent, TextEvent
n Implementation of Event Handlers
An object of the class TextArea sends, among other things, text events (see class TextField). Action
events are not emitted since the return key creates a line break.

SAP AG JA200 2-33
SAP AG 2003
TextField
<<abstract>>
Component
java. awt
TextComponent TextField
Using the TextField class, you can display and enter single-
line text fields.
Both the user and the program can show the displayed text
and change it.
TextField is derived from TextComponent.
Diagram: Frame with TextFields



n Constructors
TextField(): Creates a new text field.
TextField(int columns): Creates a new text field with the specified number of columns (width).
TextField(String text): Creates a new text field, initialized with the specified text.
TextField(String text,int columns): Creates a new text field with the specified width and initialized
with the specified text.
The columns parameter defines the width of the text field, that is, the number of displayed
characters. The number of characters to be entered is not affected by this.
n Methods
The TextField class has all the attributes and methods of the TextComponent class, and also the
following methods.
void setText(String txt)/ String getText(): The content of the text field.
void setColums(int i)/int getColumns(): The number of characters that can be displayed for the text
field.
void setEchoChar(char c)/char EchoChar(): Implements invisible input (for example,
password)setEchoCharachter(*) Defines that, no matter what button is pressed, only the masking
character * is displayed.

SAP AG JA200 2-34
SAP AG 2003
Colors
You can define the foreground color for texts and lines and the background
color for components using the following methods:
setForeground (Color.xxx);
setBackground (Color.xxx);
As of JDK 1.1, you can access the preset standard colors of the respective
host system using the static fields of the SystemColor class. Examples:
for frame ,panel, applet ,label:
setBackground (SystemColor.window);
setForeground (SystemColor.windowText);
for text field, text area:
setBackground (SystemColor.text);
setForeground (SystemColor.textText);
for buttons, and so on:
setBackground (SystemColor.control);
setForeground (SystemColor.controlText);
and the same for menus, scrollbars, and other components as well as for
special color assignments (highlight, inactive, and so on).



n Colors
You should always call the methods setForeground()/setBackground() in pairs. The color can be
specified in three ways:
- Using one of the predefined color objects, such as Color.black or Color.white.
- Using an object you have created yourself, such as
new Color(255,151,0) for orange; the three colors specify the red, green, and blue
share between 0 and 255.
- Using an object you have created yourself, such as Color.decode("#FF9900")
- Using a string parameter that defines the color as in HTML.


You specify the colors for areas, lines, and fonts in GraphicsObjects using setColor(), not using
setForeground()/setBackground().

SAP AG JA200 2-35
SAP AG 2003
Fonts and Size Specifications
Fonts
You can define the font type and font size of components using the
following method:
Font f = new Font (Fontname, Fonttype, Fontsize);
setFont (f);
Size Specifications
With most components, the correct size is derived from their content
(textstring in the case of a label or button, total of components for a
container) and therefore does not have to be specified explicitly by the
programmer (for exceptions, see note section).
With all components and containers, you can at any time query how big
the component actually is using getSize();
This method supplies an object of the type Dimension that contains the
two data fields width and height (in pixels).



n Fonts
Font names: Serif", "SansSerif", and "Monospaced (in Java 1.0: "TimesRoman", "Helvetica",
and "Courier").
Font types: Font.PLAIN (normal), Font.BOLD (bold), Font.ITALIC (italics) or together
Font.BOLD + Font.ITALIC.
Font size: Is specified as an integer in points (not in pixels), for example, 12.
n Size Specifications
If you have a window (frame or dialog), you must explicitly specify the size: setSize (width,
height); or pack();
This means that the window is made as small as possible using the layout manager so that all the
components have just enough space in it.
If you have a canvas object, you must also specify the size explicitly using the following methods.
These methods are queried by the layout manager in order to release the required space:
getMinimumSize();
getPreferredSize();
getMaximumSize();
There are other special cases where you can help the layout manager with explicit size specifications
to determine the right size. It depends on the layout manager used in each case whether and how it
uses these size specifications and converts them.

SAP AG JA200 2-36
SAP AG 2003
Layout Manager (1)
To simplify the alignment of dialog elements, AWT uses the
Layout Manager concept.
The layout manager takes care of portability to different
graphical systems, platform-independent.
The layout manager is responsible for the size and
arrangement of the dialog elements within a container.
Containers can be nested and each container in turn can have
its own layout manager.



n Method
void setLayout(LayoutManager mgr): Sets the Layout Manager for the object concerned.

SAP AG JA200 2-37
SAP AG 2003
Layout Manager (2)
In the standard version, Java provides the following layout
managers:
BorderLayout
CardLayout
FlowLayout
GridLayout
GridBagLayout
If portability is less important to you, you can do without the
implementation of a layout manager. In this case, you structure
the user interface elements manually.



n Layout Manager
BorderLayout: Distributes the dialog elements according to program specifications onto the 4
border areas and the center area of the window.
CardLayout: Is able to include several subdialogs like a pack of playing cards in a single
window, one behind the other, and to display any one of them on request.
FlowLayout: Aligns the dialog elements from the left to the right, and from the top to the bottom
in the window. "Line breaks" are executed automatically. GridLayout aligns the dialog elements
in a rectangular grid whose line and column numbers are specified when the layout manager is
created.
GridBagLayout: Enhances the abilities of GridLayout in that it enables you to create highly
complex layouts using condition objects.

SAP AG JA200 2-38
SAP AG 2003
BorderLayout
Diagram: Frame with BorderLayout
BorderLayout splits the area into 5 sections that can be
addressed using the constants NORTH, SOUTH, EAST,
WEST, and CENTER.



n Constructors
BorderLayout(): Creates a new border layout without gaps between the components.
BorderLayout(int hgap,int vgap): Creates a new border layout with the specified gaps between the
components.

The parameters hgap, vgap change the horizontal, vertical gaps between the elements.

SAP AG JA200 2-39
SAP AG 2003
CardLayout
Diagram: Frame with CardLayout
CardLayout ensures that, like in a pile of cards, only one of the
components of a container is visible at a time.
CardLayout is only appropriate in connection with event
handling.



n Constructors
CardLayout(): Creates a new CardLayout with gaps of width 0.
CardLayout(int hgap,int vgap): Creates a new CardLayout with the specified vertical and horizontal
gaps.

The parameters hgap, vgap change the horizontal, vertical gaps between the elements.
n Methods
first(Container parent)/next(Container parent)/previous(Container parent)/last(Container parent):
With these methods, you can switch back and forth between the components. show(Container
parent,String name): Displays the respective component.

SAP AG JA200 2-40
SAP AG 2003
FlowLayout
Diagram: Frame with FlowLayout
FlowLayout creates the individual elements from the left to the
right, and from top to bottom, in the sequence in which they were
added to the container.



n Constructors
FlowLayout(): Creates a new FlowLayout with central alignment and a vertical and horizontal gap of
5 units.
FlowLayout(int align): Creates a new FlowLayout with the specified alignment and a vertical and
horizontal gap of 5 units.
FlowLayout(int align,int hgap,int vgap): Creates a new FlowLayout with the specified alignment and
the specified gaps.

The align parameter specifies whether the elements of a line are to be left-aligned, right-aligned, or
centered (for this purpose, you have the constants FlowLayout.LEFT, FlowLayout.RIGHT, and
FlowLayout.CENTER at your disposal).
The parameters hgap, vgap change the horizontal, vertical gaps between the elements.

SAP AG JA200 2-41
SAP AG 2003
GridLayout
Diagram: Frame with GridLayout
GridLayout arranges the individual elements within a
rectangular grid.



n Constructors
GridLayout(): Creates a grid layout with a column for each compoent in one line.
GridLayout(int rows,int cols): Creates a grid layout with the specified number of lines and columns.
GridLayout(int rows,int cols,int hgap,int vgap): Creates a grid layout with the specified number of
lines and columns, and the specified gaps.

The parameters rows, cols define the vertical and horizontal number of elements.
The parameters hgap, vgap change the horizontal, vertical gaps between the elements.

SAP AG JA200 2-42
SAP AG 2003
GridBagLayout
Diagram: Frame with GridBagLayout
GridBagLayout is the most complicated layout manager. Here the
elements can stretch across several lines/columns of a grid.



n Constructors
GridBagLayout(): Creates a GridBagLayout.

For each component added to a GridBagLayout, you can specify layout parameters using an object
of the class GridBagConstraints.
In this way, you can set the following attributes:
int gridx,int gridy: The relative position in the grid.
double weightx,double weighty: The relative weighting of a component.
CENTER, EAST, NORTH ... : The orientation for how a component is anchored.
int gridwith, int gridheight : The number of lines that a component is to fill in horizontal/vertical
direction in the grid.
BOTH, NONE, HORIZONTAL,VERTICAL: The fill mode of a component.
int ipadx, int ipady: Specifications on inner frame distances within the grid.

SAP AG JA200 2-43
SAP AG 2003
NullLayout
Diagram: Frame with NullLayout
NullLayout allows you to position dialog elements at fixed
coordinates. You can create a NullLayout by calling the method
setLayout(null).
In this case, you leave it up to the window of the application as to
where to position the components. Here you must execute the
following steps:
Create dialog element
Define size and position
Pass on dialog element to window



n Methods
void setBounds(int x,int y,int width,int height): The parameters x,y define the position. The
parameters width, height define the size of the element.

SAP AG JA200 2-44
SAP AG 2003
Menus
Object
<<abstract>>
MenuComponent
MenuItem
MenuShortcut
Checkbox-
MenuItem
Menu
<<Interface>>
MenuContainer
<<Interface>>
ItemSelectable
java.lang
java.awt
<<Interface>>
Serializable
java.io
MenuBar
PopupMenu



n Java allows you to construct menus using several classes specially provided for this purpose.

SAP AG JA200 2-45
SAP AG 2003
Menus (2)
Objects of the Frame class and its subclasses can contain
a menu system through which the users can control
processing.
All parts of the menu system are implemented through
special classes whose objects have to be combined.
Diagram: Frame with Menu
File
New
Open
Extras
Exit
What
Yo



n Menus
Using menu bars allows the user to interact with the program. The user can choose menu options and
hence implicitly trigger events that the program must react to.

In Java you have the definition of the menu structure within the program code (in contrast to many
development systems where the definition is exported into external resource files).

SAP AG JA200 2-46
SAP AG 2003
Menu Bar (1)
1 void add(Menu m);
2 void remove(int idx);
3 void remove(MenuComponent m);
4 Menu getMenu(int idx);
5 void setMenuBar(MenuBar mb);
File
MenuBar
MenuBar
A menu bar represents the main menu of a window.



n Constructors
public MenuBar(): Creates a new menu bar.
n Methods
Line 1: Adds a menu to the menu bar.
Line 2/3: Removes an existing menu from the menu bar.
Line 4: Establishes an existing menu object.
Line 5: Includes a menu bar in a window.

SAP AG JA200 2-47
SAP AG 2003
Menu Bar (2)
1 void add(MenuItem mi);
2 void add(String label);
3 void remove(int idx);
void remove(MenuComponent m);
4 void addSeparator( );
void addSeparator(int pos);
5 MenuItem getItem( );
6 int getItemCount( );
Menu
File
New
Open
Extras
Exit
What
Yo
Menu
The parts of a menu bar are the individual menus.
New
Open
Extras
Exit
What
Yo



n Constructor
Menu(): Creates a new menu without a label.
Menu(String label): Creates a new menu with the specified label.
Menu(String label,boolean tearOff): Creates a new menu with the specified label and the
specification as to whether the menu can be "torn off".
n Methods
Line 1: Adds a menu item to the menu.
Line 2: Label here refers to the menu name. An instance of the MenuItem class is created
automatically.
Line 3: Removes an existing MenuItem object.
Line 4: Inserts a separator line.
Line 5: Access to menu entry.
Line 6: Returns the number of menu entries.

SAP AG JA200 2-48
SAP AG 2003
MenuItem, CheckboxMenuItem
1 String getLabel( );
2 void setLabel(String label);
MenuItem
1 boolean getState( );
2 void setState(boolean state);
CheckboxMenuItem
File
New
Open
Extras
Exit
What
Yo
CheckboxMenuItem
Separator
The menu items form the elementary parts of a menu.
MenuItem



n Constructor
MenuItem(): Creates a new menu entry without label and menu shortcut.
MenuItem(String label): Creates a new menu entry with the specified label, without a menu shortcut.
MenuItem(String label,MenuShortcut s): Creates a new menu entry with the specified label and
menu shortcut.
CheckboxMenuItem(): Creates a checkbox menu entry without label.
CheckboxMenuItem(String label): Creates a new checkbox menu entry with the specified label.
CheckboxMenuItem(String label,boolean state): Creates a new checkbox menu entry with the
specified label and state.
n Methods MenuItem
Line 1: Query name of an entry.
Line 2: Change name of an entry.

CheckboxMenuItem:
Line 1: Query state.
Line 2: Set state.

SAP AG JA200 2-49
SAP AG 2003
PopupMenu
Menu
java. awt
PopupMenu
Diagram: Frame with PopupMenu
Cut
Copy
Paste
PopupMenu
When you right-click a popup menu, it supplies you with the most
important actions that are available within the selected component.
Popup menus are implemented using the PopupMenu class, which
is operated like the Menu class and additionally contains the show()
method.
PopupMenu is derived from Menu.



n Constructor
PopupMenu(): Creates a new popup menu.
PopupMenu(String label): Creates a new popup menu with the specified label.

n Methods
void show(Component origin,int x,int y):
origin: The component to which the popup menu is linked.
x: x-Koordinate , relative to origin from origin.
y: y-Koordinate , relative to origin from origin.

SAP AG JA200 2-50
SAP AG 2003
Events (Event Control)
Basic principle: Events are passed from the event source only to
one of its registered event recipients that are waiting for events
of a particular type.
Event listener
Attributes
Methods
Event listener
Attributes
Methods
Event recipient / Event listener Event source / Event trigger
Interface IObserver
eventPerformed(Event ev)
Register
Deregister
EventX
The Delegation Event Model
notifies



n Event Handling
As of Java V.1.1, event handling runs as follows:
Event Trigger
An object that wants to generate events (Event Trigger) must maintain a type of internal distribution
list. This is a list of all objects (listeners) that can and want to receive event objects from the original
object.

Interface (implemented by the observer)
Defines a method (for example, eventPerformed) that is called whenever the state of the observed
object changes.

Event Listener
All these listener objects must implement a special, predefined interface (event interface). This
enables them to register with the object triggering the event.
The fact that all listener objects must implement the event interface ensures that they also contain all
event processing methods defined in the interface (general purpose of an interface).

Event
If an event occurs in the event trigger, an event object is created. Using the methods defined in the
interface, this object is then passed on to all listener objects registered with the event trigger.
Using special methods of the relevant event class, the listener objects are now able to get information
about the type and origin of an event.

SAP AG JA200 2-51
SAP AG 2003
The Delegation Event Model (1)
Event trigger
Provides methods with which listeners can be registered,
deregistered, and notified.
The listeners must implement a listener interface.
Stores the references to the listeners in an internal list.
Event Listener
Attribute
Methoden
Event Listener
Attribute
Methoden
Event listener Event trigger
Interface IObserver
eventPerformed(Event ev)
Register
Deregister



n The object that wants to generate events (event trigger) must maintain a type of internal distribution
list. This is a list of all objects (listeners) that wish to be notified about changes of state and can and
want to receive event objects.
n Events in a graphical user interface come into existence through user actions (for example, moving
the mouse, pushing buttons, and so on) and can be passed to the event listener by the respective GUI
elements. The event listener can then process the events.
n If a message is to be passed on, the processEvent() method is first called within the event source.
This method then passes on the message to specialized methods on the basis of its type.

SAP AG JA200 2-52
SAP AG 2003
The Delegation Event Model (2)
Event
Event listener
Attributes
Methods
Event listener
Attributes
Methods
Event listener Event trigger
InterfaceIObserver
eventPerformed(Event ev)
EventX notifies
As soon as a specific state has been reached in the event trigger, an
event object is created and passed on to all registered listeners
In so doing, the method defined in the listener interface is called.



n Event
If an event occurs in the event trigger, an event object is created. Using the methods defined in the
interface, this object is then passed to all listener objects registered with the event trigger.
Using special methods of the relevant event class, the listener objects are now able to get information
about the type and origin of an event.

SAP AG JA200 2-53
SAP AG 2003
The Delegation Event Model (3)
Event listeners
Implement a listener interface
Register themselves with the event trigger (or are registered)
Are notified by the event trigger when an event occurs and process the
passed event object
Event trigger and event listeners can be the same object, but do not
have to be.
Event listener
Attributes
Methods
Event listener
Attributes
Methods
Event listener Event trigger
InterfaceIObserver
eventPerformed(Event ev)
Register
Deregister
EventX
notifies



n Event Listener
All listener objects must implement a specially predefined interface (event interface). This enables
them to register with the object triggering the event.
The fact that all listener objects must implement the event interface ensures that they also contain all
event processing methods defined in the interface (general purpose of an interface).
The names of these (listener) methods depend on the type of event class.
An event source sends events to a listener only if the latter is registered with the event trigger

Registration is done using special methods. (add<xxx>Listener())

SAP AG JA200 2-54
SAP AG 2003
Event Types (1)
The different event types are represented by a hierarchy of event
classes.
AWTEvent
java.awt.event
EventObject
ActionEvent
AdjustmentEvent
ComponentEvent
ItemEvent
java.util
TextEvent
ContainerEvent
FocusEvent
<<abstract>>
InputEvent
PaintEvent
WindowEvent
KeyEvent
MouseEvent
java.awt
Semantic Low-level
events events



n The class java.util.EventObject represents a general superclass of all types of events that can be
exchanged between programs.
Their most important feature is the ability to store an object that has triggered an event and to specify
it using the method getSource().

n AWT Event Classes
The hierarchy of the AWT-specific event classes begins with the class AWTEvent. Here there is a
distinction between the following hierarchies:

Low-Level Events
Underneath the class ComponentEvent, these classes are responsible for the transfer of messages that
come from windows or dialog elements.

Semantic Events
The other classes are not linked to a particular GUI element. They transfer "more important" events,
such as changing a state or executing a command.

Within an event class, you can have several events grouped together.

SAP AG JA200 2-55
SAP AG 2003
Event Types (2)
Semantic events
ActionEvent Commands
AdjustmentEvent Adjustments
ItemEvent Status changes
TextEvent Text changes
Low-Level Events
ComponentEvent Change, move size, and so on
ContainerEvent Add, delete element
FocusEvent Receive, lose focus
KeyEvent Press, release key
MouseEvent Click, move mouse, and so on
WindowEvent Open, close window, and so on



n Continuation of AWT Event Classes

Low-Level Events
These events typically occur in great numbers, for example, when a menu command is selected.
Here, an object of the class MouseEvent is created for each mouse movement and each
pushing/releasing the button.

Semantic Events
These events only occur for very particular events and in less numbers than for low-level events.

SAP AG JA200 2-56
SAP AG 2003
Assignment: Event source / Event type



n The above table shows the assignment between visual AWT components (event trigger) and the
event type(s) triggered by them.

SAP AG JA200 2-57
SAP AG 2003
Event Listeners (1)
So that an object can receive events, it must implement a series
of methods that can be called by the event trigger where it has
registered itself.
java.util
<<Interface>>
EventListener
java.awt.event
<<Interface>>
ActionListener
<<Interface>>
AdjustmentListener
<<Interface>>
ItemListener
<<Interface>>
TextListener
<<Interface>>
FocusListener
<<Interface>>
KeyListener
<<Interface>>
MouseListener
<<Interface>>
MouseMotionListener
<<Interface>>
ComponentListener
<<Interface>>
ContainerListener
<<Interface>>
WindowListener



n Event Listener
For each event class there is one EventListener interface. This interface defines a separate method
for each event type of the respective event class.

The fact that the event listeners implement certain interfaces ensures that the respective
methods exist and can be called by the event triggers.


SAP AG JA200 2-58
SAP AG 2003
Event Listeners (2)
Methods that have to be implemented when the interface is used.
ActionListener void actionPerformed(ActionEvent event); Action was triggered
AdjustmentListener void adjustmentValueChanged(AdjustmentEvent ev); Value was changed
ComponentListener void componentHidden(ComponentEvent event); Component became invisible
void componentMoved(ComponentEvent event); Component was moved
void componentResized(ComponentEvent event); Component size was changed
void componentShown(ComponentEvent event); Component became visible
ContainerListener void componentAdded(ContainerEvent event); Component was added
void componentRemoved(ContainerEvent event); Component was removed
FocusListener void focusGained(FocusEvent event); Component receives focus
void focusLost(FocusEvent event); Component loses focus
ItemListener void itemStateChanged(ItemEvent event); Status has changed
KeyListener void keyPressed(KeyEvent event); Key was pressed
void keyReleased(KeyEvent event); Key was released
void keyTyped(KeyEvent event); Key pressed and released
MouseListener void mouseClicked(MouseEvent event); Mouse-button clicked and released
void mouseEntered(MouseEvent event); Mouse pointer enters component
void mouseExited(MouseEvent event); Mouse pointer leaves component
void mousePressed(MouseEvent event); Mouse-button pressed
void mouseReleased(MouseEvent event); Mouse-button released
MouseMotionListener void mouseDragged(MouseEvent event); Mouse dragged with pressed button
void mouseMoved(MouseEvent event); Mouse was moved
TextListener void textValueChanged(TextEvent event); Text was changed
WindowListener void windowActivated(WindowEvent event); Window was activated
void windowClosed(WindowEvent event); Window was closed
void windowClosing(WindowEvent event); Window closing
void windowDeactivated(WindowEvent event); Window was deactivated
void windowDeiconified(WindowEvent event); Window was restored
void windowIconified(WindowEvent event); Window reduced to symbol
void windowOpend(WindowEvent event); Window was opened



n Interface Methods
As soon as a class implements an interface, it must implement the methods contained in it.
Here methods that are not absolutely required are given an empty method body. To avoid several
such statements, Java provides a series of adapter classes (see next slide).

SAP AG JA200 2-59
SAP AG 2003
Event Listeners (3)
Adapter classes represent an "empty" implementation of the
respective interface.
java.util
<<Interface>>
EventListener
java.awt.event
<<Interface>>
ActionListener
<<Interface>>
AdjustmentListener
<<Interface>>
ItemListener
<<Interface>>
TextListener
<<Interface>>
FocusListener
<<Interface>>
KeyListener
<<Interface>>
MouseListener
<<Interface>>
MouseMotionListener
<<Interface>>
ComponentListener
<<Interface>>
ContainerListener
<<Interface>>
WindowListener
<<abstract>>
ComponentAdapter
<<abstract>>
ContainerAdapter
<<abstract>>
FocusAdapter
<<abstract>>
KeyAdapter
<<abstract>>
MouseAdapter
<<abstract>>
MouseMotionAdapter
<<abstract>>
WindowAdapter
Object
java.lang



n Adapter Classes
The task of an adpater class in Java consists of providing empty method bodies for an implemented
interface. In this way, they can always be used whenever only part of the methods from an interface
is required. For this purpose, you derive a new class from the adapter class and override the required
methods instead of implementing the corresponding interface with all methods. The remaining
(empty) methods are provided by the Basis class.

Java provides an adpater class for each of the low-level event recipients.

SAP AG JA200 2-60
SAP AG 2003
Example (1)
Pressing one of the buttons in window 1 triggers an ActionEvent
that is processed by window 2:
Event listener
Event trigger
Event type



n Example
The following example shows how you can have a class react within an application to an event that
is triggered in another class.

First of all, both windows are displayed. As soon as a button is clicked in the EventEmitter, this
sends an event to all the recipient objects it has registered, and these then react to the event.

SAP AG JA200 2-61
SAP AG 2003
Example (2)
Step 1: The listener object decides
- Which component it wants to listen to
- Which events it wants to receive
Step 2: The listener implements the corresponding
interfaces and provides the methods requested
therein.
<<Interface>>
ActionListener
MyObserver
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class MyObserver extends Frame
5 implements ActionListener {
6 . . .
7 public void actionPerformed(
8 ActionEvent event ) {
8 . . .
9 }
10 . . .
11 }



n Step 1
The listener object must decide which components it wants to listen to and for which events it wants
to be notified.
n Step 2
Accordingly, the listener must implement the required interfaces and methods.

In the example above: The listener MyObserver wants to be notified whenever a button is clicked in
the class MyEventEmitter. For this purpose, MyObserver must implement the interface
ActionListener (line 5) and provide the method actionPerformed(...) (line 7).

SAP AG JA200 2-62
SAP AG 2003
Example (3)
Step 3: The listener registers through the corresponding
addXXXListener() method at the event source (or is registered).
MyObserver
1 import java.awt.*;
2 import java.awt.*;
3 class MyEventEmitter extends Frame {
4 ...
5 MyObserver observer = new MyObserver();
6 ...
7 for (int idx=0; idx<5; idx++) {
8 Button b = null;
9 add(b = new Button("Button "+idx));
10 b.addActionListener(observer);
11 }
12 ...
13 }
Button
<<Interface>>
ActionListener



n Step 3
The listener must be registered with the event trigger. This is done using the corresponding
addXXXListener() methods for the components that can trigger an event.

In the example above: The listener MyObserver is registered as an observer for each button of the
class MyEventErmitter (line 10).

SAP AG JA200 2-63
SAP AG 2003
Example (4)
Step 4: The event source triggers an event and the component
sends a special event object to all registered listeners.
1 public class Button extends Component
3 implements Accessible {
3 ...
4 protected void processEvent
( ActionEvent event ) {
5 ...
6 }
7 ...
8 }
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class MyObserver extends Frame
5 implements ActionListener {
6 . . .
7 public void actionPerformed(
8 ActionEvent event ) {
8 . . .
9 }
10 . . .
11 }
<<Interface>>
ActionListener
MyObserver
ActionEvent



n Step 4
Pressing one of the buttons triggers an event in the Button component. The component creates an
ActionEvent object and informs all the listeners it has registered with it.

In the above example: Button 1 was pressed. The component informs all the listeners registered with
it (in this case an object of the MyObserver class) and calls their actionPerformed() method; this
passes on a corresponding event object that the observer can then evaluate.

SAP AG JA200 2-64
SAP AG 2003
Button & ActionEvent
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class DButton extends STDFrame
5 implements ActionListener {
6 ...
7 // Constructor
8 public DButton(boolean exitFlag) {
9 super(frame with buttons and events...", exitFlag);
10 setLayout(new FlowLayout());
11 for (int idx=0; idx <5; idx ++) {
12 Button b= null;
13 add(b= new Button("Button "+ idx));
14 b.addActionListener(this);
15 }
16 this.setVisible(true);
17 }
18
19 public void actionPerformed(ActionEvent event) {
20 String cmd= event.getActionCommand();
21 for (int idx=0; idx<5; idx++) {
22 String but= "Button "+idx;
23 if (cmd.equals(but)) {
24 System.out.println("Button "+idx+" pressed");
25 }
26 }
27 }
28 }
Diagram: Frame with Button



n Event Types of the Button Class
ActionEvent, ComponentEvent, FocusEvent, KeyEvent, MouseEvent
A button emits, among other things, an action event whenever a button (button area) is pressed.
n Implementation of the Event Handlers
void addActionListener(ActionListener al): To react to the event, an ActionListener must be
registered by calling this method (line 14).
abstract void actionPerformed(ActioneEvent event): As soon as an action event has been sent, the
method actionPerformed() is executed with an argument of the type ActionEvent in the registered
event recipient (line 19). The ActionEvent provides the method actionPerformed(): -- you can use
this to query the label of the button. If you do not wish the Action command to be the same as the
label of the button, you can change it in the Button class by calling void setActionCommand (String
command);

SAP AG JA200 2-65
SAP AG 2003
Canvas & KeyEvent
1 import java.awt.*;
2
3 public class DCanvasMy extends Canvas{
4
5 private Color color;
6
7 public DCanvasMy() {
8 super();
9 }
10
11 public void paint(Graphics g) {
12 g.setColor(getColor());
13 g.fillRect(0,0,getSize().width,
14 getSize().height);
15 }
16
17 public void setColor(Color color) {
18 this.color= color;
19 }
20
21 public Color getColor() {
22 return color;
23 }
24
25 } // class
Diagram: Frame with Canvas
1 import java.awt.*;
2 import java.awt.event.*;
3
4 public class DCanvas extends com.esap.tut2.demos.STDFrame
5 implements KeyListener{
6 private DCanvasMy myCanvas= new DCanvasMy();
7 int idx= 0;
8 Color color[]= {Color.red, Color.green, Color.blue};
9
10 public static void main (String args[]) {
11 DCanvas aDemo= new DCanvas(true);
12 }
13
14 public DCanvas(boolean exitFlag) {
15 super("frame with a canvas...",exitFlag);
16 myCanvas.setSize(150,150);
17 myCanvas.setColor(color[idx]);
18 myCanvas.requestFocus();
19 add(myCanvas);
20 addKeyListener(this);
21 setVisible(true);
22 }
23
24 // KeyListener methods
25 public void keyTyped(KeyEvent event) {
26 if (idx==color.length) idx= 0;
27 myCanvas.setColor(color[idx]);
28 myCanvas.repaint();
29 Idx++;
30 }
31 public void keyPressed(KeyEvent event) {}
32 public void keyReleased(KeyEvent event){}
33
34 } // class



n Event Types of the Canvas Class
ComponentEvent, FocusEvent, KeyEvent, MouseEvent

n Implementation of the Event Handlers
void addKeyListener(KeyListener kl): The canvas object registers itself "with itself" as a listener
(line 20). In this way, it must implement the KeyListener interface and the corresponding methods
(lines 25, 26, 31).

SAP AG JA200 2-66
SAP AG 2003
Checkbox & ItemEvent
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class DCheckbox extends STDFrame
5 implements ItemListener {
6 ...
7 // Constructor
8 public DCheckboox(boolean exitFlag) {
9 ...
10 for (int idx=0; idx <5; idx ++) {
11 Checkbox cb= null;
12 if((idx%2)==0) {
13 ...
14 }
15 cb.addItemListener(this);
16 }
17 this.setVisible(true);
18 }
19
20 public void itemStateChanged(ItemEvent event) {
21 Checkbox cb= (Checkbox)event.getItemSelectable();
22 System.out.println("Label= "+cb.getLabel()+
23 "State= "+cb.getState());
24 }
25 }
Diagram: Frame with Checkbox



n Event Types of the Checkbox Class
ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent

Objects of the Checkbox class can react immediately to a change in state.
void addItemListener(ItemListener il): For this purpose, an object that implements the ItemListener
interface must be registered with the checkbox by calling addItemListener:

abstract void itemStateChanged(ItemEvent ie): As soon as the state of a checkbox changes, an
ItemEvent is emitted. Here the method itemStateChanged is called in the event recipient with an
argument of the type ItemEvent.

itemSelectable getItemSelectable():The ItemEvent provides the method getItemSelectable, which
you can use to establish which checkbox triggered the event.

SAP AG JA200 2-67
SAP AG 2003
Choice & ItemEvent
Java
Java
C++
Delphi
Smalltalk
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class DCheckbox extends STDFrame
5 implements ItemListener {
6
7 ...
8
9 // Constructor
10 public DCheckboox(boolean exitFlag) {
11 super(frame with checkboxes...", exitFlag);
12 Choice choice= new Choice();
13 choice.addItemListener(this);
14 choice.addItem(Java);
15 ...
16 }
17
18 public void itemStateChanged(ItemEvent event) {
19 Choice choice= (Choice) event.getItemSelectable();
20 String s1= choice.getSelectedItem();
21 String s2= (String)event.getItem();
22 System.out.println("choice.getSelectedItem()= "+s1);
23 System.out.println("event.getItem()= "+s2);
24 }
25 }
Diagram: Frame with Choice



n Event Types of the Choice Class
ComponentEvent, FocusEvent, KeyEvent, MouseEvent
A choice always emits an Item event whenever an element has been selected.

n Implementation of the Event Handlers
void addItemListener(ItemListener il): To react to the event, you must register an ItemListener by
calling this method (line 13).
abstract void itemStateChanged(ItemEvent e): As soon as an Item event has been emitted, the
method itemStateChanged() is executed in the registered event listener with an argument of the type
ItemEvent (line18).
The ItemEvent provides the method ItemSelectable getItemSelectable(); so that it is possible to react
to the change of selection. Using this method, you can acquire a Choice element and determine items
using the method getSelectedItem() (line 20).
Object getItem(): Using this method, you can display the selected element as a string (line 21).

SAP AG JA200 2-68
SAP AG 2003
List & ActionEvent, ItemEvent
1 ...
2 class DList extends STDFrame
3 implements ActionListener, ItemListener {
4 ...
5 // Constructor
6 public DList(boolean exitFlag) {
7 super(frame with a list(box) and events...", exitFlag);
8 List list= new List();
9 list.addActionListener(this);
10 list.addItemListener(this);
11 list.addItem(Ford Prefect);
12 ...
13 }
14
15 public void ActionPerformed(ActionEvent event) {
16 System.out.println(ActionListener, event.getActionCommand()=+
17 event.getActionCommand());
18 }
19
20 public void ItemStateChanged(ItemEvent event) {
21 List list= (List) event.getItemSelectable();
22 String str= list.getSelectedItem();
23 int pos= ((Integer) event.getItem()).intValue();
24 System.out.println("ItemListener, list.getSelectedItem()= "+str);
25 System.out.println("ItemListener, event.getItem()= "+pos);
26 }
27 }
Diagram: Frame with Choice



n Event Types of the List Class
ActionEvent, ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent
A list emits, among other things, action and item events:
an Action event if an element in the list was selected using a mouse double-click.
an Item event if an element in the list was selected (using mouse or cursor).
In the example above, a double-click on entry 1 first triggers an item event and then an action event.
n Implementation of the Event Handlers
This runs the same as, for example, the Choice class. As soon as an ItemEvent is triggered, the
method getItemSelectable of the ItemEvent behaves in exactly the same way as Choice and returns a
List object.

public Object getItem( ): The return value of this method can be interpreted as follows: The method
returns the item as an Integer object that can be converted to an int using intValue() (see line 23).

SAP AG JA200 2-69
SAP AG 2003
Scrollbar & AdjustmentEvent
Diagram: Frame with text field and scrollbars
1 import java.awt.*;
2 import java.awt.event.*;
3
4 class DScrollbar extends STDFrame implements AdjustmentListener{
5 ...
6
7 // Constructor
8 public DList(boolean exitFlag) {
9 super(frame with scrollbars...", exitFlag);
10 setLayout(new GridLayout(4,1));
11 sbRed.addAdjustmentListener(this);
12 sbGreen.addAdjustmentListener(this);
13 sbBlue.addAdjustmentListener(this);
14 add(text);
15 ,,,
16 }
17
18 public void adjustmentValueChanged(AdjustmentEvent event) {
19 Color color= new Color(sbRed.getValue(),sbGreen.getValue(),sbBlue.getValue());
20 text.setForeground(color);
21 }
22 }



n Event Types of the Scrollbar Class
AdjustmentEvent, ComponentEvent, FocusEvent, KeyEvent, MouseEvent

n Implementation of the Event Handlers
void addAjustmentListener( ): A scrollbar sends, among other things, adjustment events to its
listeners; these, in turn, implement the interface AdjustmentListener and register themselves by
calling addAdjustmentListener().
abstract void adjustmentValueChanged(AdjustmentEvent e): The Adjustment event causes this
method to be called in the listener object and passes an object of the type AdjustmentEvent.

The object AdjustmentEvent has, among other things, the method getAdjustable(); which you can
use to establish the triggering scrollbar, and getValue(), which you can use to establish the current
value of the scrollbar. In addition, you have the method getAdjustmentType(); at your disposal,
which provides information on the user action.
Here you can query the following constants:
AdjustmentEvent.UNIT_IN[DE]CREMENT: Value is decreased by one unit when you click the
button.
AdjustmentEvent.BLOCK_IN[DE]CREMENT: Value is decreased by one page.
AdjustmentEvent.TRACK: Value is changed by moving the scroller.

SAP AG JA200 2-70
SAP AG 2003
TextField & ActionEvent, TextEvent
1 ...
2 class DTextField extends STDFrame implements ActionListener, TextListener {
3 ...
4 // Constructor
5 public DTextField(boolean exitFlag) {
6 super(frame with textfields...", exitFlag);
7 Panel panBottom= new Panel();
8 ...
9 Panel panEdit= new Panel();
10 panEdit.setLayout(new GridLayout(2,1));
11 TextField tf= new TextField("Arthur",20);
12 tf.addActionListener(this);
13 tf.addTextListener(this);
14 ...
15 }
16
17 public void actionPerformed(ActionEvent event) {
18 System.out.println("event.getActionCommand()= "+event.getActionCommand());
19 }
20
21 public void textValueChanged(TextEvent event) {
22 TextField tf= (TextField)event.getSource();
23 System.out.println("event.getSource().getText()= "+tf.getText());
24 }
25 }
Diagram: Frame with TextFields



n Event Types of the Textfield Class
ActionEvent, ComponentEvent, FocusEvent, ItemEvent, KeyEvent, MouseEvent

n Implementation of the Event Handlers
ActionEvent: As soon as the user presses the return key in the text field, the text field generates an
action event. The method getActionCommand() of the action event returns the content of the text
field.
TextEvent: Is generated each time the text field is changed.

void addTextListener(): Used to register a listener for text field events.
abstract void textValueChanged(TextEvent e): The text event calls this method in the listener and
passes an object of the type TextEvent.TextEvent is derived from AWTEvent and inherits the
methods getID() und getSource(). In this way, you can get the respective text field using getSource()
and access its text content using getText().

SAP AG JA200 2-71
SAP AG 2003
MenuItem, MenuShortcuts & Events
With the help of the MenuShortcut class, you can define
platform-independent accelerator keys for menu entries as
of JDK 1.1.
Diagram: Frame with MenuItem and ShortCut
1 ...
2 MenuItem mnItem_New, ...;
3 MenuShortcut mnSc_New;
4
5 menuBar= new MenuBar();
6 menu_File= new Menu("File");
7 mnSc_New= new MenuShortcut(KeyEvent.VK_N);
8 mnItem_New= new MenuItem("New,mnSc_New);
9 ...
10
11 setMenuBar(menuBar);
12 menuBar.add(menu_File);
13 mnItem_New.setActionCommand("New");
14 menu_File.add(mnItem_New);
13 ...
New Ctrl+N
Open
Extras
Exit
MenuShortcut



n Constructor
MenuShortcut(int key): Creates a new shortcut for the specified key.
MenuShortcut(int key, boolean useShiftModifier): Creates a new shortcut for the specified key.
The first constructor expects the virtual key code of the required shortcut key. The transfer of a
function key is only possible if its virtual key codes allow conversion to upper-case letters (for
example, VK_DELETE).
The parameter useShiftModifier in the second constructor defines that the shortcut will only take
effect if you press the "Shift" key as well.

Step 1 (line 3): First create an instance of the class MenuShortcut.
Step 2 (Line 7): Attach the shortcut to a menu item MenuItem(String label,MenuShortcut mns);
Step 3 (Line 13): Due to a bug in the AWT, the method void setActionCommand(String
command); must be called after the definition of a shortcut in order to define the string that is sent to
the ActionListener when the accelerator is triggered (otherewise a null object would be sent).

SAP AG JA200 2-72
SAP AG 2003
PopupMenu & ActionEvent, MouseEvent
Cut
Copy
Paste
1 ...
2 public class DPopupMenuEvent extends com.esap.tut2.demos.STDFrame
3 implements ActionListener {
4 PopupMenu ppMenu;
5 MenuItem mnItem_Cut, mnItem_Copy, mnItem_Paste;
6 ...
7 // Constructor
8 public DNullLayout(boolean exitFlag) {
9 super(frame with popupmenu and event...", exitFlag);
10 ppMenu= new PopupMenu();
11 mnItem_Cut= new MenuItem("Cut");
12 mnItem_Copy= new MenuItem("Copy");
13 mnItem_Paste= new MenuItem("Paste");
14
15 mnItem_Cut.addActionListener(this);
16 mnItem_Copy.addActionListener(this);
17 mnItem_Paste.addActionListener(this);
18 ppMenu.add(mnItem_Cut);
19 ppMenu.add(mnItem_Copy);
20 ppMenu.add(mnItem_Paste);
21 add(ppMenu);
22 enableEvents(AWTEvent.MOUSE_EVENT_MASK);
23 setVisible(true);
24 }
25
26 public void processMouseEvent (MouseEvent event) {
27 if(event.isPopupTrigger()) {
28 ppMenu.show(event.getComponent(), event.getX(), event.getY());
29 }
30 super.processMouseEvent(event);
31 }
32
33 public void actionPerformed(ActionEvent event) {
34 System.out.println("event.getActionCommand()=
35 "+event.getActionCommand());
36 }
37 ...



n Calling a Popup Menu
For this purpose, the following steps are necessary:
Step 1 (line 18/20): The instantiated popup menu is linked through the method add() to the
component that is to react to mouse clicks for the call concerned.
Step 2 (line 22): In the component, the handling of mouse events must be enabled (call for
enableEvents()).
Step 3 (line 26): The method processMouseEvent must be overwritten. Here each mouse event must
be queried using isPopupTrigger as to whether it is the event for calling the popup menu. If so, the
popup menu can be displayed using show().
n enableEvents
enableEvents() enables a component to receive events without having to have a listener interface
implemented.

Normally, however, this should not happen! (explanation on the next page)

SAP AG JA200 2-73
SAP AG 2003
Draft Design for Event Transactions (1)
The event recipient implements the required EventListener
interfaces, including the CallBack methods, and registers at
the event source.
The event recipient defines local or anonymous classes which,
in turn, implement an EventListener or are derived from an
adapter class.
The GUI code and event handling are distributed to various
classes.
In the component class, the methods that are required for
receiving and distributing the events are overridden.

2
3
1
1
4



n Options for Message Traffic
Java supplies the above options in order to display the respective message traffic between event
trigger and listener.
Thes draft templates are presented on the following pages.

SAP AG JA200 2-74
SAP AG 2003
Draft Design for Event Transactions (2)
1
1
The event recipient implements the required EventListener
interfaces, including the CallBack methods, and registers at
the event source.
Diagram: Frame that reacts to KeyEvent
1 ...
2 public class DEventDP_1_Event extends com.esap.tut2.demos.STDFrame
3 implements KeyListener {
4 public DEventDP_1_Event() {
5 super("event design pattern, 1",exitFlag);
6 addKeyListener(this);
7 setVisible(true);
8 }
9
10 public void paint(Graphics g) {
11 g.drawString("Press ESC to quit...",30,50);
12 }
13
14 public void keyTyped(KeyEvent event) {}
15 public void keyReleased(KeyEvent event){}
16 public void keyPressed(KeyEvent event) {
17 if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
18 setVisible(false);
19 dispose();
20 }
21 }
22 } // class



n Option 1
In the examples shown here, there is only one class:
Line 6: Here the event source is linked to the event listener, that is, the class registers itself as an
event listener. The prerequisite is that the corresponding event interface is implemented. This takes
place in line 4 as well as in
Lines14-21: - the interface methods are implemented here. Since the class should only react to a
button click, only the method keyPressed is coded. The other method bodies remain empty.
Line 16: This is the code that is run through after a KeyEvent is triggered.
Advantages/Disadvantages
+ Simple implementation
+ No further classes required
- No separation between GUI and application logic.
- Since separate Listener classes must be registered for each event type, and their methods
therefore must be implemented, code can very easily beome complex.

You should only use this option for smaller applications that only need limited enhancement.

SAP AG JA200 2-75
SAP AG 2003
Draft Design for Event Transactions (3)
The event recipient defines local classes which, in
turn, implement an EventListener or are derived from
an adapter class.
2a
Diagram: Frame that reacts to KeyEvent
1 ...
2 public class DEventDP_2_Event extends com.esap.tut2.demos.STDFrame {
3 // Constructor
4 public DEventDP_2_Event() {
5 super("event design pattern, 2, local class",false);
6 addKeyListener(new LocalKeyListener());
7 setVisible(true);
8 }
9
10 public void paint(Graphics g) {
11 g.setFont(new Font("Arial", Font.BOLD,16));
12 g.drawString("press ESC to quit...",30,50);
13 }
14
15 class LocalKeyListener extends KeyAdapter {
16 public void keyPressed(KeyEvent event) {
17 if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
18 setVisible(false);
19 dispose();
20 }
21 }
22 } // local class
23
24 } // class



n Option 2a
With the option shown here, you have as event trigger a class that defines a local class for event
handling, which in turn is derived from an adapter class.
Line 6: The event source is linked at this point with the event listener, that is, the separate local class
LocalKeyAdapter is registered as event listener.
Line15-21: The local class LocalKeyAdapter is derived from the class KeyAdapter. In this way, all
the required method bodies are available as empty bodies and you now only need to overwrite the
methods that you actually require.
The local class has access to all methods of the surrounding class and can therefore close the
window with setVisible(false).

Advantages/Disadvantages
+ Simple implementation
+ Derivation of event listener from an adapter class avoids empty method bodies and thus also
unnecessary coding.

- No separation between GUI and application logic.

You should use this option if it is appropriate to group together trigger and listener. Together with
the next option, this option is the procedure recommended in the JDK documentation.

SAP AG JA200 2-76
SAP AG 2003
1 ,,,
2 public class DEventDP_3_Event extends com.esap.tut2.demos.STDFrame {
3
4 // Constructor
5 public DEventDP_3_Event() {
6 super("event design pattern, 3, anonymous class",false);
7 addKeyListener(
8 new KeyAdapter() {
9 public void keyPressed(KeyEvent event) {
10 if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
11 setVisible(false);
12 dispose();
13 }
14 }
15 } // anonymous class
16 );
17 setVisible(true);
18 }
19
20 public void paint(Graphics g) {
21 g.setFont(new Font("Arial", Font.BOLD,16));
22 g.drawString("press ESC to quit...",30,50);
23 }
24
25 } // class
Draft Design for Event Transactions (4)
The event listener defines anonymous classes that, in
turn, implement an EventListener or are derived from
an adapter class.
Diagram: Frame that reacts to KeyEvent



n Option 2b
In the option shown here, you have as event trigger a class that defines an anonymous class for event
handling; this, in turn, is derived from an adapter class.
Anonymous classes are also local classes that are defined, without a class name, for passing an
object to a method, or defined as their return value within a single statement. They are
derived from existing classes or they implement existing interfaces.
Line 7: At this point, the event source is linked with the event listener, that is, an anonymous class is
defined within a statment. The class is derived from the KeyAdapter class and can be registered as
event listener.
The anonymous class, too, has access to all methods of the surrounding class and can therefore
close the window with setVisible(false).

Advantages/Disadvantages
(See anonymous classes on the previous page)
+ No separate class definition required
- Not clearly arranged if complex event handling

You should use this option if it is appropriate to group together trigger and listener. Together with
the previous option, this option is the procedure recommended in the JDK documentation.

SAP AG JA200 2-77
SAP AG 2003
Draft Design for Event Transactions (5)
The GUI code and event handling are distributed to different
classes.
3
A1 ...
A2 public class DEventDP_4_MainEvent {
A3 DEventDP_4_GuiEvent gui;
A4 DEventDP_4_AppEvent app;
A5
A6 public static void main (String args[]) {
A7 app= new DEventDP_4_AppEvent();
A8 gui= new DEventDP_4_GuiEvent(app);
A9 }
A10
A11 } // class
B1 ...
B2 public class DEventDP_4_AppEvent implements KeyListener {
B3 public DEventDP_4_AppEvent() {
B4 super();
B5 System.out.println("Event Listener, Constructor");
B6 }
B7
B8 public void keyPressed(KeyEvent event) {
B9 System.out.println("Event Listener, catched event");
B10 Frame source= (Frame)event.getSource();
B11 if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
B12 source.setVisible(false);
B13 source.dispose();
B14 }
B15 }
B16 public void keyReleased(KeyEvent event) {}
B17 public void keyTyped(KeyEvent event) {}
B18 } // class
C1 ...
C2 public class DEventDP_4_GuiEvent extends STDFrame {
C3 public DEventDP_4_GuiEvent(KeyListener app) {
C4 super("event design pattern, 4",false);
C5 System.out.println("Event Emitter, Constructor");
C6 addKeyListener(app);
C7 setVisible(true);
C8 }
C9
C10 public void paint(Graphics g) {
C11 g.setFont(new Font("Arial", Font.BOLD,16));
C12 g.drawString("press ESC to quit...",30,50);
C13 }
C14 } // class



n Option 3
With this option, the program codes for GUI and the application logic are separated. Therefore there
are several classes that are responsible for a particular subarea in each case.
Class DEventDP_4_MainEvent: Contains only the main method and instantiates both other classes.
Class DEventDP_4_AppEvent: This class becomes the event listener when it implements the
KeyListener interface. It summarizes the program logic that is run through whenever a corresonding
event is triggered.
Classe DEventDP_4_GuiEvent: This class is responsible for the GUI display and represents the
event source.
Watch out for the sequence:
Line A7/8: In the class DEventDP_4_MainEvent, you first define an instance of the class
DEventDP_4_AppEvent (as event listener). Its reference then serves as a parameter for the
instantiation of an object of the class DEventDP_4_GuiEvent:
Line C6: The class DEventDP_4_GuiEvent registers the event listener. For this purpose, it
references the class DEventDP_4_AppEvent.
Line B8: As soon as an appropriate event occurs, the corresponding Listener methods are called
from the event trigger. They are then passed to the KeyEvent object of the message initiator. In this
way, the listener finds out who the event trigger is.

SAP AG JA200 2-78
SAP AG 2003
Draft Design for Event Transactions (6)
In the component class, the methods that are required for
receiving and distributing the events are overridden.
Diagram: Frame that reacts to KeyEvent
Normally, this
should not
happen!
4
1 ...
2 public class DEventDP_5_Event extends com.esap.tut2.demos.STDFrame {
3
4 public DEventDP_5_Event() {
5 super("event design pattern, 5",false);
6 enableEvents(AWTEvent.KEY_EVENT_MASK);
7 setVisible(true);
8 }
9
10 public void paint(Graphics g) {
11 g.setFont(new Font("Arial", Font.BOLD,16));
12 g.drawString("press ESC to quit...",30,50);
13 }
14
15 public void processKeyEvent(KeyEvent event) {
16 if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
17 setVisible(false);
18 dispose();
19 }
20 super.processKeyEvent(event);
21 }
22
23 } // class



n Option 4
Overriding the event handlers in the event sources is another means of reacting to messages. .
Since the Delegation Event Model is circumvented here, this option should not be used in the
normal case.
Line 15: First, one of the methods process<xxx>Event(<xxx>Event event) needs to be overridden.
Line 20: It is important that the method in the Basis class with the same name is called in order
to ensure standard behavior!
processEvent() or process<xxx>Event are called if:
- an event listener was registered through the corresponding add<xxx>Listener method.
- the event type was explicitly activated by calling the method enableEvents().
enableEvents
enableEvents() enable a component to receive events without having to have a Listener interface
implemented.
The following bit masks are available as parameters:
ACTION_EVENTMASK, ADJUSTMENT_EVENT_MASK, COMPONENT_EVENT_MASK,
FOCUS_EVENT_MASK, ITEM_EVENT_MASK, KEY_EVENT_MASK,
MOUSE_EVENT_MASK, MOUSE_MOTION_EVENT_MASK, TEXT_EVENT_MASK,
WINDOW_EVENT_MASK

SAP AG JA200 2-79
SAP AG 2003
Graphics Programming
java.awt
Color
Cursor
Dimension
Font
Graphics
<<abstract>>
Image
Point
Polygon
Rectangle
SystemColor
Object
java.lang
Graphics programming is a further important part of the AWT.
This includes:
Drawing graphics on appropriate paint areas
(for example, java.awt.Canvas),
Outputting formatted text in different
fonts, font sizes
Animations
Representation and manipulation of screen data
Use of colors and templates



n Graphics Programming with the AWT
Graphics programming is supported in Java by a series of classes.
The graphics context Graphics represents a uniform interface to different output media and
contains character methods.
The Component class and the subclasses derived from it contain a paint area (for example,
Canvas).
The classes Dimension, Point, Polygon, Rectangle, and so on, model simple, graphical objects
and their size.
The classes Color and SystemColor support color programming.
The classes Font and FontMetrics support font programming.

SAP AG JA200 2-80
SAP AG 2003
Graphics Class (1)
Object
java.lang
Graphics
java. awt
Graphics2D
Using Graphics2D, you can display text and screens in a
professional manner.
If you have components of the Canvas type, you must
explicitly specify using the paint method which graphical
elements are to be represented.
The paint method works with an object of the type
Graphics.
Graphics is derived from Object.



n If you wish to output professional images and text (for example, when developing your own
component or a game), you should use the Graphics2D class. This belongs to the Java2D API, which
contains other features. See also: http://java.sun.com/docs/books/tutorial/2d/index.html.

SAP AG JA200 2-81
SAP AG 2003
Graphics Class (2)
Color and font setColor ( Color );
setFont ( Font );
Lines drawLine (x1, y1, x2, y2);
Contin. curves / curves drawRect (x1, y1, width, height);
drawPolygon (x[], y[], n);
drawPolyLine (x[], y[], n);
drawOval (x1, y1, width, height);
drawArc (x1, y1, width, height, startangle, angle);
Areas fillRect (x1, y1, width, height);
fillPolygon (x[], y[], n);
fillOval (x1, y1, width, height);
fillArc (x1, y1, width, height, startangle, angle);
Texts (String) drawString (String, x1, y1);
Screens (Image) drawImage (Image, x1, y1, this);



n The Graphics Class

Color and Font
Before you draw lines, fill out areas, or output strings, you must define the color and possibly also
the font type for the graphic commands immediately following.

Lines
drawLine(x1,y1,x2,y2); draws a straight line from the first point to the second point. If both points
are identical, only one point is drawn (1 pixel). The line width is always 1 pixel. You can create
wider lines by drawing several parallel lines, each 1 pixel apart, beside each other, or using
fillPolygon().

Continuous Curves or Curves
The parameter list usually specifies first the upper left corner point and then the width and height of
the figure or the rectangle to be circumscribed. To be more precise: the rectangle has a width of
(width+1) pixels and a height of (height+1) pixels). You get circles as a special case of ellipses with
the same width and height.

Canvases
Canvases are filled in color using the fill methods. The fill methods always have the same
parameters as the corresponding draw methods.

Texts (String)
drawString (String, x1, y1); represents a single-line text string. Automatic line-break is not possible
here.

SAP AG JA200 2-82
SAP AG 2003
Color Class
Object
java.lang
Color
java. awt
SystemColor
Colors are represented in Java by the Color class.
Each color object represents a color that is uniquely
defined by its RGB values.
You can create colors by instantiating a color object and
passing the required RGB value to the constructor.
Graphics is derived from Object.



n Constructors
Color(int r,int g,int b)/Color(float r,float g,float b):
The constructor with the int parameters expects the color values as integers in the range of 0 through
255. If you have a constructor with the float parameters, each of the values must be in the range
between 0.0 to 1.0. 0.0 means that the color part is completely missing, and 1.0 stands for maximum
color intensity (matches the integer color value 255).
Alternatively, the Color class provides a series of static color objects that can be used directly:
static Color white [|lightGray|gray|darkGrey|black|red|blue|green |yellow|magenta|cyan|orange|pink]
Using the methods int getRed(); , int getGreen(); , int getBlue(); you can establish the RGB values
from an existing color object.


SAP AG JA200 2-83
SAP AG 2003
Font Class
Object
java.lang
Font
java. awt
Diagram: Frame with diff. fonts
Fonts are output, by default, in a system-specific, standard
font. If you wish to use a different font than the one in the
text output, you must first create a suitable object of the
Font class and assign it to the Graphics object used.
Fonts are usually unportable; therefore they should be
used carefully.
Font is derived from Object.



n public void paint(Graphics g)
Font font;
String arfonts[] = "Serif", "SansSerif", "Monospaced";
for (int i=0; i<arfonts.length; ++i)
font = new Font(arfonts[i], Font.PLAIN,36);
g.setFont(font);
g.drawString(arfonts[i], 10,30 + (i+1)*(36+5));
}
}

SAP AG JA200 2-84
SAP AG 2003
Summary
You should now be able to:
l Create a graphic user interface with the classes
of the package java.awt and its subpackages.
l Create programs for event handling.




SAP AG JA200 2-85
AWT Exercises


Chapter AWT
Topic: Simple AWT GUI for Vehicle List

At the conclusion of this exercise, you will be able to:
Create a simple GUI with AWT classes.

Note:
The course JA200 GuiKit is based on a vehicle model that is discussed in detail in the
course JA100 StartUpKit. The classes of this course are available as .jar files and can
be used throughout the remainder of the exercises, provided you have made the relevant
project settings in the IDE.

Since you only use defined interfaces of JA100 classes in the exercises, you require no
knowledge of the internal structure and functions of these classes.

In the following exercises, you will program a graphical user interface (GUI), step by step, and
thereby use classes from the vehicle model.

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab02 + 1. Take a look at the graphic(s).
JVIEWER

2-1 Create the main screen MainScreen.

Open the package com.sap.epf.ja200.exc.lab02.
Define the class MainScreen. The class is to be public and belong to the package
com.sap.epf.ja200.exc.lab02.
Import the following classes/packages.
import java.awt.*;
import java.awt.event.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.model.*;
Derive your class or implement the following interfaces.
extends Frame


Define the following attributes:
Modifier Type Name
private List carList
private Button btnDetails
private Panel btnPanel

SAP AG JA200 2-86


Define the following constructor (empty at first):
Modifier Name/parameter list
pulic MainScreen()


Define the following methods (empty at first):
Modifier Return type Name/parameter list
private void initialize()
private void initializeMenu()
public
static
void main( String[] args )
2-2 Implement the method(s):

private void initialize()
Create a BorderLayout for the MainScreen. Then set
a GridLayout with 7 lines and a column for the panel pnlButton.

Create the List, the Button, and the Panel.
Set the status of the Button to inactive using the method setEnabled(boolean
b).

Add the Button to the panel pnlButton. Add the List and the Panel to the
MainScreen, the List at the position Center, and the Panel at the position East.

Set the height of the MainScreens to 200 and the width to 400. Make the
MainScreen visible.


SAP AG JA200 2-87
2-3 Implement the Constructor.

public MainScreen()
Call the constructor of the superclass and enter here a title (string) for the
MainScreen. Afterwards, call the initialize method.

2-4 Implement the main method.

Create an object of the class MainScreen, Compile and test the program.

2-5 Create a menu line

Define the following additional attributes in the class MainScreen:
Modifier Type Name
private MenuBar menuBar
private Menu mnFile
private Menu mnEdit
private Menu mnHelp
private MenuItem miNew
private MenuItem miExit
private MenuItem miOpen
private CheckboxMenuItem cbmiNeed
Implement the method(s):

private void initializeMenu()
Create the respective objects. Create the following menu structure:

+-- File
+-- New
+-- Open
+-- Exit

+-- Edit

+-- Help
+ -- cbmiNeed

Set a Separator between open and exit. The menu help contains the
CheckboxMenuItem need.
Now, finally, add the MenuBar to the MainScreen.
Test your program.


SAP AG JA200 2-88
2-6 Add a Listener to the MenuItem exit. The application is to be canceled as soon
as this menu entry is selected.

For this purpose, define the internal class LocalMenuItemListener in the class
MainScreen. This class is to implement the interface ActionListener. Define the
actionPerformed(...)method so that the application is canceled.


2-7 Write an inner class LocalEventHandler.

Derive this from the class WindowAdapter. Overwrite the method
windowClosing(WindowEvent event) so that the program is canceled as soon as
the window is closed (System.exit(0)).
At the beginning of the class MainScreen, declare an object of the type
LocalEventHandler. Add an object of this class as WindowListener to your
MainScreen in the constructor.

Test your program.

2-8 Create a car list.

To be able to display the data from the vehicle model in the list,
you must use the predefined classes in the JAR files JA100.jar.
The vehicle data is read from the files and then objects are created on the basis of the
class com.sap.epf.ja100.persist,PersistManager. These vehicle objects of
the class com.sap.epf.ja100.model.VehicleRow are summarized in a so-called
vehicle pool. This is one of the classes that the interface
com.sap.epf.ja100.model.IPool implements and internally controls the vehicle
data using dynamic data containers.
You receive, therefore, the vehicle data through the PersistManager, which returns
to you a reference to a vehicle pool.



SAP AG JA200 2-89
At the beginning of the class MainScreen, declare the following attributes:
Modifier Type Name
private IPool vehiclePool
private VehicleRow vehicleRow
private DialogDetail detail
private PersistManager pMan
The IPool interface or the VehicleRow class are both in the package
com.sap.epf.ja100.model; the class PersistManager is in the package
com.sap.epf.ja100.persist.
The class DialogDetail is already predefined in the package
com.sap.epf.ja200.exc.lab02.


2-9 Implement a new constructor.

public MainScreen( PersistManager pMan )
Define the constructor in such a way that an argument of the type PersistManager
must be specified as well. First, call the superclass constructor again.
Initialize the reference variable pMan in the constructor with the appopriate passed
parameter.
Using the statement pMan.getBusObjectPool("vehicle"); access a valid
VehiclePool and pass the reference to it to the reference variable vehiclePool.

Call the initializeMenu() and initialize() method.
Suppress the default constructor of the class MainScreen.


2-10 Change the initialize() method.

Now, in the initialize method, import the VehicleRow lines of the IPool object into
your List. For this purpose, you must first pass the individual lines of the IPools to
the previously declared VehicleRow object in a loop. The class VehicleRow
provides you with get methods, which you can use to access the attributes
Model(vehicle model) and Day(indicator). Read these attributes and import their
content into a string. Add this string to the List.



SAP AG JA200 2-90
2-11 Change the class
com.sap.epf.ja200.lab02.exc.CarControlApp.

This class is predefined. Create an object of the type MainScreen in the constructor
after the line persistMgr.loadBusObjects();. You have declared this object
previously at the beginning of the program.

Test your program.


2-12 Enhance the event handling in the MainScreen class so that it displays details for a
vehicle.

Now implement the interfaces ActionListener and ItemListener in the inner
class LocalEventHandler of the class MainScreen.

Add the LocalEventHandler to the button details. Overwirte the method
itemStateChanged(ItemEvent event) of the LocalEventHandler so that,
when you click on a line, the status of the details button is set to active.

Also add to the carList the Listener LocalEventHandler.
Overwrite the method actionPerformed(Action Event event) of the
ActionListeners so that, whenever the button details is pressed, an object of the
class DialogDetail (which already exists) is created.
For this purpose, first get the current index of List. Using this index, you can get a
valid VehicleRow instance using the method getRow(int idx) of the VehiclePool.
Using this reference list, you can now call the DialogDetail constructor.

Test your program.


SAP AG JA200 2-91
AWT Solutions


Unit: AWT
Topic: Simple AWT GUI for Car List

2-1 Create the main screen MainScreen.

package com.sap.epf.ja200.exc.lab02;

import java.awt.*;
import java.awt.event.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.model.*;

public class MainScreen extends Frame {

private List carList;
private Button btnDetails;
private Panel pnlButton;

public void initialize () {
}

public void initializeMenu () {
}

public MainScreen (){
}

public static void main (String[] args){
}
}


SAP AG JA200 2-92
2-2 Implement the method(s), constructor, main method.

package com.sap.epf.ja200.exc.lab02;

import java.awt.*;
import java.awt.event.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.model.*;

public class MainScreen extends Frame {

private List carList;
private Button btnDetails;
private Panel pnlButton;

public void initialize () {
this.setLayout( new BorderLayout() );

carList = new List();
btnDetails = new Button ("details");
btnDetails.setEnabled(false);
pnlButton = new Panel();
pnlButton.setLayout( new GridLayout(7,1) );
pnlButton.add( btnDetails );

this.add(pnlButton, BorderLayout.EAST);
this.add(carList, BorderLayout.CENTER);
this.setSize(400,200);
this.setVisible(true);

public MainScreen (){
super("Fahrzeuge / vehicles");
initialize();
}

public static void main (String[] args){
MainScreen ms = new MainScreen();
}
}


SAP AG JA200 2-93
2-5 Create a menu line

. . .
public class MainScreen extends Frame {
. . .

private void initializeMenu() {
menuBar = new MenuBar();
mnFile = new Menu("File");
miNew = new MenuItem("New");
miExit = new MenuItem("Exit");
miOpen = new MenuItem("Open");
mnEdit = new Menu ("Edit");
mnHelp = new Menu ("Help");
cbmiNeed = new CheckboxMenuItem (" I need help");
mnHelp.add(cbmiNeed);

setMenuBar(menuBar);
menuBar.add(mnFile);
mnFile.add(miNew);
mnFile.add(miOpen);
mnFile.addSeparator();
mnFile.add(miExit);
menuBar.add(mnEdit);
menuBar.add(mnHelp);
}

public MainScreen (){
super("Fahrzeuge / vehicles");
initializeMenu();
initialize();
}
}



SAP AG JA200 2-94
2-6 Add a Listener to the MenuItem exit. The application is to be canceled as soon
as this menu entry is selected.

public class MainScreen extends Frame {

private void initializeMenu() {
. . .
miExit = new MenuItem("Exit");
miExit.addActionListener(
new LocalMenuItemListener() );
. . .
}
. . .

public class LocalMenuItemListener
implements ActionListener {
public void actionPerformed (ActionEvent event){
System.exit(0);
}
}

}

















SAP AG JA200 2-95
2-7 Write an inner class LocalEventHandler.

public class MainScreen extends Frame {
. . .
private LocalEventHandler handler;

public void initialize () {
this.setLayout( new BorderLayout() );

handler = new LocalEventHandler();
this.addWindowListener(handler);
. . .
}

. . .

public class LocalEventHandler
extends WindowAdapter {
public void windowClosing(WindowEvent event){
System.exit(0);
}
}
}


SAP AG JA200 2-96
2-9 Implement a new constructor.

public class MainScreen extends Frame {
. . .
private IPool vehiclePool;
private VehicleRow vehRow;
private PersistManager pMan;
private DialogDetail detail;

. . .
public MainScreen (PersistManager pMan ){
super("Fahrzeuge / vehicles");

this.pMan = pMan;
vehiclePool = pMan.getBusObjectPool("vehicle");

initializeMenu();
initialize();
}
}

















SAP AG JA200 2-97
2-10 Change the initialize() method.

public class MainScreen extends Frame {
. . .
public void initialize () {
. . .
int poolSize = vehiclePool.getPoolSize();
carList = new List();

for (int i=0; i<poolSize; i++){
vehicleRow = (VehicleRow)vehiclePool.getRow(i);
String text =
vehicleRow.getVehicle().getVhclModel()
+ " "
+ vehicleRow.getVehicle().getVhclTag();
carList.add(text);
}

this.setVisible(true);
}
}


SAP AG JA200 2-98
2-11 Change the class com.sap.epf.ja200.lab02.exc.CarControlApp.

public class CarControlApp {
. . .
public MainScreen mainScreen;
public CarControlApp() {
try {
. . .
persistMgr.loadBusObjects();
mainScreen = new MainScreen( persistMgr );
} catch (Exception exc) {
System.out.println("Error loading Properties ");
System.out.println(exc.getMessage());
}
}
}



SAP AG JA200 2-99
2-12 Extend the event handling in the MainScreen class so that it displays details for a
vehicle.

public class CarControlApp {
. . .
public void initialize () {
this.setLayout( new BorderLayout() );
handler = new LocalEventHandler();
this.addWindowListener(handler);
carList = new List();
carList.addItemListener(handler);
btnDetails = new Button ("details");
btnDetails.setEnabled(false);
btnDetails.addActionListener(handler);
. . .
}

public class LocalEventHandler extends WindowAdapter
implements ActionListener, ItemListener {
. . .
public void actionPerformed (ActionEvent event){
String cmd = event.getActionCommand();
if (cmd.equals("details")){
int pos = carList.getSelectedIndex();
vehicleRow =
(VehicleRow)vehiclePool.getRow(pos);
detail = new DialogDetail(vehicleRow);
}
}

public void itemStateChanged(ItemEvent event){
btnDetails.setEnabled(true);
}
} // inner class
}





SAP AG JA200 3-1
SAP AG 2003
l Properties
l Containers
l Labels and Text Fields
l Menus
l Buttons
l Dialogs
l Tables and Trees
l Events
Swing




SAP AG JA200 3-2
SAP AG 2003
Course Overview Diagram
Introduction
Preface
AWT
Swing
Browser-Based GUI
Development
SWT




SAP AG JA200 3-3
SAP AG 2003
Unit Objectives
At the conclusion of this unit, you will be able to:
l Describe the general architecture of Swing
l Work with the most important components of Swing
l Use the Model View Controller architecture
l Use the events of the Swing components for
programming




SAP AG JA200 3-4
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 1
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-5
SAP AG 2003
Java Foundation Classes (JFC)
AWT
Java 2D
Accessibility
Drag and Drop
Swing
Look & Feel



n The Java Foundation Classes represent a comprehensive class library in Java, as published by Sun.
n The AWT API was already discussed in the last unit.
n Java 2D concerns classes and functions for painting graphics and text. Numerous functions are
available with which bitmap graphics can be painted, rotated, distorted, filtered, and so on.
n The Accessibility API helps disabled people access Java software. This is done, for example, by
enlarging screen sections (zoom function), speech recognition, or read/write devices for Braille.
n The Drag&Drop function, as known from Microsoft Windows, is enabled between Java applications
and between Java and non-Java applications.
n Swing is a library for creating graphical user interfaces (GUIs). Swing is based on AWT, but also
party replaces it.
n Look & Feel classes and functions are closely connected with Swing. They enable a display (look) of
the component that is independent from the actually used class (such as JButton for a switch). You
can also add additional functions (feel) to an existing component, such as the display of a screen in a
combination list field.

SAP AG JA200 3-6
SAP AG 2003
Swing
Swing = originally the code name of the project
Swing 0.2
Swing 1.0.3
Swing 1.1 Beta
Swing 1.1 Beta 3
Swing 1.1
Swing 1.1.1
-
-
JDK 1.2 Beta 4
JDK 1.2 Release Candidate 1
Java 2 SDK, Standard Edition, v1.2
Java 2 SDK, Standard Edition, v1.2.2
Contained in JDK



n The first two Swing releases were contained in JFC 1.1, but not yet in JDK (Java 2 Release).

SAP AG JA200 3-7
SAP AG 2003
From AWT to Swing
AWT: Heavyweight components
java.awt
Button
<<abstract>>
Toolkit
java.awt.peer
<<Interface>>
ButtonPeer
Swing: Lightweight components
Operating system A
Operating system B
Operating system C
NativeButton
Naming convention J<<name of AWT component>>
Exceptions: Choice (AWT) = JComboBox (Swing)
FileDialog (AWT) = FileChooser (Swing)
Event handling and MVC
New events (javax.swing.event.*)
New procedure of Model View Controller approach
Numerous additional components
for example trees, tables



n AWT and heavyweight components
To execute an AWT-based program, the Java Interpreter uses a platform-specific implementation of
the AWT classes that is not written in Java.
On every execution platform (such as Microsoft Windows, MAC-OS, Unix, and so on), an AWT
component requires a so-called peer, which controls the display and functions of the component and
is written in the native code of the execution platform. The advantage is that the native peer classes
make the interface faster. Unfortunately, the programs occasionally show strange side effects on the
different operating systems. Amongst other things, the programmer also no longer has complete
control over the appearance of a GUI if the relevant programs are running on a different platform to
that of the development environment.
n Swing and lightweight components
In contrast with AWT, Swing components only make use of platform-specific GUI resources in a
limited manner: Apart from top-level windows, dialogs, and primitive graphical operations, all GUI
elements are created by Swing itself. This was achieved by introducing the lightweight components
in JDK 1.1. A lightweight component has no peer. Therefore, there is no special implementation of
the system on Windows, MacOS, or X11, for example. The advantage is that this method is more
platform-independent. A lightweight component can be transparent and no longer has to fit into a
rectangular area. The disadvantage is that there is a negative effect on performance. Java takes on the
complete event handling and the components are displayed using primitive paint operations.

SAP AG JA200 3-8
SAP AG 2003
Top-Level and Second-Level Components
java.awt
<<abstract>>
Component
<<abstract>>
Container
javax.swing
<<abstract>>
JComponent
Window
JButton
JWindow
Frame JFrame
Dialog JDialog
JButton
JButton
...
2
nd
-level
components
Top-level
components



n Swing components are not a complete substitute for AWT (Abstract Windowing Toolkit). Instead,
they are based on AWT and merely replace the application components.
n We differentiate between top-level and second-level components. The former generally represent a
window which contains the 2nd-level components (also known as basic components).
n JWindow, JFrame, and JDialog are top-level components. All are derived from their individual
counterparts in AWT.
n JComponent is the basis class of all 2nd-level Swing components. However, JComponent is derived
from java.awt.Container and not from java.awt.Component.

SAP AG JA200 3-9
SAP AG 2003
Visual Overview
Top-level components
JApplet
2nd-level components, general purpose container
JComponent
JScrollPane
JWindow
JDialog JFrame
JPanel
JSplitPane JTabbedPane
JToolBar




SAP AG JA200 3-10
SAP AG 2003
Visual Overview (2)
2nd-level components, special purpose container
JInternalFrame
Panes (RootPane, LayeredPane, and so on)
2nd-level components, menus
JCheckBox
MenuItem
JMenu JMenuBar JPopup
Menu
JRadioBut
tonMenuItem




SAP AG JA200 3-11
SAP AG 2003
Visual Overview (3)
2nd-level components, labels and text fields
JLabel
2nd-level components, buttons, combo boxes, and lists
JComboBox
JButton JCheckBox
JTextField
JTextArea
JRadio
Button
JList




SAP AG JA200 3-12
SAP AG 2003
Visual Overview (4)
2nd-level components, additional, non-editable components
Border*
2nd-level components, additional, editable components
JTable
JColor
Chooser
JFile
Chooser
JProgress
Bar
JScrollbar
JOption
Pane
JTree
JSlider JToolTip



n * = not a separate component. Each component can have a frame (border).

SAP AG JA200 3-13
SAP AG 2003
Look & Feel
Motif Look & Feel
Windows
Cross-platform
Also: "Java Look and Feel"
"Metal"



n Pluggable Look & Feel (PL&F) is one of the most interesting features of Swing. It enables you to
influence the visual appearance as well as the behavior of components.
n The same basic component is always used (for example, an expandable list, JComboBox). However,
the list display can even be changed during runtime.
n For the following operating system GUIs, Swing already includes L&F:
Mac
Motif
Windows
n There is also a cross-platform L&F ("Metal") that is also delivered with Swing This is the default
setting.
n It is also possible to create your own L&F.

SAP AG JA200 3-14
SAP AG 2003
Look & Feel (2)
1 try {
2 UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName());
3 SwingUtilities.updateComponentTreeUI(this);
4 }
5 catch (Exception e) }
Setting cross-platform Look & Feel
1 try {
2 UIManager.setLookAndFeel(com.sun.java.swing.plaf.motif.MotifLookAndFeel);
3 SwingUtilities.updateComponentTreeUI(this);
4 }
5 catch (Exception e) }
Motif Look & Feel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
Windows
com.sun.java.swing.plaf.mac.MacLookAndFeel
Macintosh
UIManager.getSystemLookAndFeelClassName()
Current platform



n To activate a specific L&F use the setLookAndFeel method of the UIManager class.
n You should also call the updateComponentTreeUI method of SwingUtilities with the
current top-level component (usually JFrame instance) if you want to change the appearance at
runtime.
n For licensing reasons, the Macintosh-L&F cannot currently be used under Microsoft Windows; the
corresponding packages are not in the JFC.

SAP AG JA200 3-15
SAP AG 2003
Model View Controller Architecture (MVC)
View
Con-
troller
Model
The controller acts as a link between the
view and the model. It receives keyboard
and mouse events and triggers the
required measures for changing the
model and the view.
The model contains the data of the dialog
element and saves its state
The view is responsible for the graphical
display of the component
Delegate



n Model View Controller (MVC) is a design pattern that is often used when creating GUIs.
n In the Model View Controller paradigm, there are normally three objects that communicate with one
another: Model (data model), view (visualization), and controller (manager).
n With MVC, the data model (object) and the actual display component (object) are encapsulated
separately. This leads to strict object-orientation, which in turn results in advantages when
programming:
A data model object (model) can serve as a source for several display components
The model class can take care of data retrieval itself
The database access routines can be better encapsulated and hence the object-oriented
programming concept can be better implemented
n Additionally, in the case of MVC, a controller should manage the input/output and their change
conditions. However, since this leads to high degree of complexity, controller and view are often
combined.
n In Swing, controller and view are also combined to form so-called "delegates".

SAP AG JA200 3-16
SAP AG 2003
Model View Controller Architecture (MVC) (2)
View
Con-
troller
Model
The model, for example
DefaultTableModel class:
The delegate (view and controller),
for example JTable class:
Delegate
JTable
DefaultTableModel
- Holds the data in a collection
- Provides methods for data retrieval
- Is responsible for the visualization of the
data
- Can react to keyboard and mouse events
Model Manufacturer LicensePlate lD



n The above example shows the use of MVC with the component JTable (table).
n An object of the class JTable requires a model (for example DefaultTableModel, though other
classes are also possible) which holds display/input data for it.
n JTable is not a pure view, since an object of this class receives and processes keyboard input/mouse
actions itself, for example.
n We will not go into any further detail here, as JTable will be discussed later.

SAP AG JA200 3-17
SAP AG 2003
Swing Packages
javax.accessibility
Additional input/
output possibilities
javax.swing.border
General components,
adapters, interfaces
Borders for
components
Component for color
selection
Special Swing event
classes
Component for file
selection
Classes for L&F
implementation
JTable, interfaces,
and basic classes for
tables
javax.swing.text
Text editor
components and
document classes
HTML editor
components and
document classes
javax.swing.text.html
RTF editor
components and
document classes
javax.swing.rtf
JTree class
(hierarchical list)
Basis classes for
undo/redo functions
javax.swing.undo
javax.swing.event
javax.swing
javax.swing.table
javax.swing.colorchooser javax.swing.filechooser
javax.swing.plaf.*
javax.swing.tree




SAP AG JA200 3-18
SAP AG 2003
Class Overview
java.swing.* JComponent
AbstractButton JButton
JMenuItem
JCheckBoxMenuItem
JMenu
JToggleButton
JRadioButtonMenuItem
JCehckBox
JComboBox
JLabel
JList
JMenuBar
JPanel
JPopupMenu
JScrollBar
JScrollPane
JTextComponent
JEditorPane
JTextArea
JTextField
JTextPane
JPasswordField
JColorChooser
JFileChooser
JInternalFrame
JLayeredPane
JDesktopPane
JOptionPane
JProgressBar
JRootPane
JSeparator
JPopupMenu.Separator
JToolbar.Separator
JSlider
JSplitPane
JTabbedPane
JTable
JToolbar
JToolTip
JTree
JViewport
JInternalFrame.JDesktopIcon
JRadioButton




SAP AG JA200 3-19
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 2
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-20
SAP AG 2003
A significant difference between the main windows in AWT and
Swing lies in their component structure
In AWT, the components are placed directly in the window
A Swing main window JFrame, JDialog, JWindow, JApplet (and
JInternalFrame) has a single main component RootPane that
takes on all other components
RootPane is of the type JRootPane and contains the following
components:
A GlassPane derived from Container
A LayeredPane derived from JLayeredPane, which in turn contains:
A ContentPane derived from Container
A menu bar derived from JMenuBar
Pane Levels



n The top-level containers JFrame, JDialog, JWindow, JApplet (and JInternalFrame) contain a
hierarchy of panels, which are shown above for the example JFrame.
n Each JFrame object first aggregates a RootPane object. This is initially the central starting point for
painting screen elements. It is the main container that holds all other containers or components.
n The LayeredPane (Typ JLayeredPane) enables a Z order of the components. This means that
containers can be cascaded.
n ContentPane (type Container) and MenuBar (type JMenuBar) are contained directly in LayeredPane.
n New components must be added to the ContentPane and not directly to JFrame.
n The GlassPane can be used to paint directly on the JFrame.

SAP AG JA200 3-21
SAP AG 2003
Pane Levels (2)
When you create a window, the RootPane (and with it the
GlassPane, LayeredPane, and ContentPane it contains) is created;
the menu bar remains empty by default
JFrame
RootPane
LayeredPane
MenuBar
ContentPane
GlassPane
1 //...Adding a screen element to a JFrame:
2 JFrame jFrame = new JFrame();
3 JButton jButton = new JButton();
4 jFrame.getContentPane().add(jButton);



Line 2: A main window is created
Line 3: A button is created and is to be placed in the main window
Line 4: getContentPane is used to call the ContentPane of the main window.
It provides getter/setter methods with which dialog elements (here, the button) can be
placed.

SAP AG JA200 3-22
SAP AG 2003
JFrame
In regards to function, the JFrame class corresponds to
java.awt.Frame
Separate panel architecture
JFrame contains several panel instances for itself. You are also
able to paint directly on the JFrame (using GlassPane).
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
Frame JFrame
JFrame with title line



n JFrame is the most important of the so-called "top-level containers". JFrame can take on other
components, but is not contained in another component itself. Starting from here, a hierarchy of
containers ("containment hierarchy") is constructed.

SAP AG JA200 3-23
SAP AG 2003
JFrame: Reaction To Closing a Window
WindowConstants.DO_NOTHING_ON_CLOSE:
Merely triggers event
WindowConstants.HIDE_ON_CLOSE (default):
Window is only hidden
WindowConstants.DISPOSE_ON_CLOSE:
Frame is destroyed
JFrame.EXIT_ON_CLOSE:
Whole application is exited
As of JDK
1.3
In the first three cases, defined WindowListeners are supplied with events
to which they can react
1 public void setDefaultCloseOperation(int state);
2 public int setDefaultCloseOperation();



n In contrast with AWT, when you click the cross at the top right corner of a window in Swing, it is
closed automatically. You do not have to write a WindowAdapter, as is the case in AWT. However,
you can change this behavior using the setDefaultCloseOperation(int operation) method.
n Using DefaultCloseOperation you can automatically hide the window (HIDE_ON_CLOSE, default),
destroy it (DISPOSE_ON_CLOSE), or even end the application (EXIT_ON_CLOSE).
n However, the latter constant is only defined and implemented as of JDK 1.3.
n In all cases, except for the last, the WindowClosed method is called for all registered
WindowListener objects:
myFrame.addWindowListener(new WindowAdapter(){
public void windowClosed(WindowEvent e){
System.exit(0);
}
});

SAP AG JA200 3-24
SAP AG 2003
The JDialog class represents a component for your own
dialog windows
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
Window
JDialog Dialog
JDialog with title line
It can be modal, frames cannot
1 JDialog dialog = new JDialog();
2 dialog.setModal( true );
JDialog



n JDialog enables you to use a window as a so-called modal (locking) window. This means that all
entries or mouse clicks in other windows are ignored and the modal window is always displayed on
top.
n To set a a dialog to modal you can either use the relevant constructor of the JDialog class or call the
setModal(..) method.

SAP AG JA200 3-25
SAP AG 2003
Tooltips
JComponent
JComponent contains the following new features:
Frames (borders)
Keyboard shortcuts
Look & Feel
Properties
Additoinal layout support
Accessibility
Screen buffering
Other help functions
java.lang java.awt
Object
<<abstract>>
Component
Container JComponent
Javax.swing
If you want to create your own Swing component, you
should generally derive it from JComponent



n Tooltips: Can be set using the setToolTipText(String aString) method.
n Frames: The setBorder(Border border) method allows you to activate a frame previously created
using the BorderFactory class.
n Shortcut keys: JComponent supports these with the registerKeyboardAction method.
n Look & Feel: Every JComponent has a ComponentUI object that is responsible for painting and
layout functions.
n Properties: You can use the methods putClientProperty and getClientProperty to add user-defined
properties to the component.
n Layout: The methods setPreferredSize, setMinimumSize, setMaximumSize, SetAlignmentX, and
setAlignmentY are new.
n Accessibility: JComponent supports the Accesibility API to enable you to connect special
input/output devices to the component.
n Screen buffering: JComponent saves the graphic that it is to paint.
n Other: Many new methods have been added, such as getX and getY.

SAP AG JA200 3-26
SAP AG 2003
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JPanel
JPanel is used to arrange a number of dialog elements under
the control of a layout manager
Unlike with main windows, there is no ContentPane in this case.
The dialog elements and the layout manager are assigned to the
panel directly.
JPanel



n The JPanel class is often used as a container object for dialog components. Apart from the inherited
functions of JComponent, Container, Component, and Object, there are no significant other
functions.

SAP AG JA200 3-27
SAP AG 2003
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo-
nent
JToolBar
JToolBar
The JToolBar class is used to create toolbars
JToolBar can take on any Swing components (often a set of
buttons), which can be arranged horizontally or vertically
Toolbar JToolBar with buttons
Above: "Docked"
Below: "Floating"



n JToolbar is a container that, like JPanel, is inserted into another container.
n JToolBar offers you the "floating" feature with which the toolbar floats on top of the application in
its own window.
n Apart from the functions/features already mentioned, there is another interesting property:
Orientation of the type int.
There are two constants for this: HORIZONTAL and VERTICAL.

SAP AG JA200 3-28
SAP AG 2003
JScrollPane with
JEditorPane
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JScroll
Pane
JViewPort and JScrollPane can be used by other components
(JList, JTextArea, JTable, and so on) to make their contents
visible section by section using a movable window ("scroll"
function)
The following possibilities exist:
1 JTextArea myTextArea = new JTextArea();
2 JScrollPane scrollPane = new JScrollPane( myTextArea );
// alternative:
3 JScrollPane scrollPane = new JScrollPane();
4 scrollPane.setViewportView( myTextArea );
// alternative:
5 scrollPane.getViewport().setView(myTextArea);
6 Container cont = getContentPane();
7 cont.add(scrollPane, "Center");
JScrollPane



n Swing components are not a complete substitute for AWT (Abstract Windowing Toolkit). Instead,
they are based on AWT and merely replace the application components.
n The peer system with which the Java components (such as java.awt.Component) are mapped to the
different operating system GUI SDKs (Software Development Kits) remains intact. Therefore, there
is no "native" code in Swing.

SAP AG JA200 3-29
SAP AG 2003
Main screen of example application
"CarControlApp" with JSplitPane
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JSplit
Pane
JSplitPane is a panel with which you can arrange two components
horizontally or vertically
The components are separated by a (visible) separator
JSplitPane
Left pane
Right pane
Splitter



n JSplitPane is a control derived from JComponent that can contain two subscreens. The display area
of the two screens can be changed by moving the splitter (divider).
n There are two possible modes: JSplitPane.HORIZONTAL_SPLIT and
JSplitPane.VERTICAL_SPLIT. You can set the desired mode using the setOrientation property of
the type int.

SAP AG JA200 3-30
SAP AG 2003
JSplitPane (2): Important Methods
JSplitPane
1 Component get-/set- LeftComponent / RightComponent
2 Component get-/set- TopComponent / BottomComponent
3 int get-/set- Orientation
4 int get-/set- DividerSize
5 boolean get-/set- OneTouchExpandable
In the JSplitPane class, the following methods are defined,
amongst others:
. . .
1 JSplitPane splitPane = new JSplitPane();
2 JPanel pnlCenterLeft = new JPanel();
3 pnlCenterLeft.setBackground(Color.white);
4 JPanel pnlCenterRight = new JPanel();
5 JPanel pnlCenterRight.setBackground(Color.black);
6 splitPane.setLeftComponent( pnlCenterLeft );
7 splitPane.setRightComponent( pnlCenterRight );
8 splitPane.setDividerLocation( 150 );
9 splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
10 splitPane.setOneTouchExpandable( true );
11 splitPane.setOpaque( false );
. . .
Demo



Line 1: For HORIZONTAL_SPLIT: The two components contained in SplitPane
Line 2: For VERTICAL_SPLIT: The two components contained in SplitPane
Line 3: Orientation of splitter: JSplitPane.HORIZONTAL_SPLIT or
JSplitPane.VERTICAL_SPLIT
Line 4: Size of splitter in pixels
Line 5: Specifies whether the splitter can be expanded with a single click.
Depending on the Look&Feel, there are different default settings. In Java Look&Feel, this
property is false.

As well as the above, there are also the following features:
With the ContinousLayout property you specify whether or not the components in JSplitPane are
to be repainted while the splitter is moved.
The properties LastDividerLocation (get/set): The last position of the splitter.
MaximumDividerLocation and MinimumDividerLocation (both only get): The
minimum/maximum position of the splitter. These are set implicitly.

SAP AG JA200 3-31
SAP AG 2003
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JTabbed
Pane
JTabbedPane
Main screen of example application
"CarControlApp" with JTabbedPane
JTabbedPane allows you to create dialogs that contain a number
of tabs
These "subdialogs" can then be individually selected using the
list of tabs at the side



n Swing components are not a complete substitute for AWT (Abstract Windowing Toolkit). Instead,
they are based on AWT and merely replace the application components.
n The peer system with which the Java components (such as java.awt.Component) are mapped to the
different operating system GUI SDKs (Software Development Kits) remains intact. Therefore, there
is no "native" code in Swing.

SAP AG JA200 3-32
SAP AG 2003
JTabbedPane (2)
JTabbedPanes contain JPanels and organize them in tabs
The contained JPanels can be changed dynamically
JTabbedPane



n TabbedPanes organize components in tabs.
n For this purpose, the components are usually first contained in JPanel instances. JTabbedPane can
contain objects of the type JComponent (and its derivations). Therefore, many methods of
JTabbedPane work with JComponent.
n The above example shows a JTabbedPane containing four tabs. Each tab contains a JPanel with a
different number of buttons and tables with different contents.
n The tabs can be changed dynamically at runtime.


SAP AG JA200 3-33
SAP AG 2003
JTabbedPane (3)
JTabbedPane
1 addTab, insertTab, remove, removeTabAt, removeAll
2 indexOfComponent, indexOfTab(String s), indexOfTab(Icon)
3 Attribute SelectedIndex, SelectedComponent (also get)
4 Attribute ComponentAt, TitleAt, IconAt, DisabledIconAt,
BackgroundAt, ForegroundAt, EnabledAt
In the JTabbedPane class, the following methods and
attributes are defined, amongst others:
. . .
1 JTabbedPane tabbedPane = new JTabbedPane();
2 Color[] colors = { Color.blue, Color.cyan, Color.red,
3 Color.magenta, Color.yellow };
4 for( int idx = 0; idx<colors.length; idx++ ) {
5 JPanel panel = new JPanel();
6 panel.setBackground( colors[idx] );
7 tabbedPane.add(""+idx, panel);
8 }
9 this.getContentPane().add(tabbedPane);
. . .
Demo



Line 1: Add, delete, insert tabs
Line 2: Define the tab index
Line 3: Information about current tab
Line 4: Properties of a specific tab
n The following properties and methods work with an object of the type JComponent that represents a
single tab:
addTab, insertTab, removeTab, indexOfComponent
SelectedComponent, ComponentAt.
n However, you can also address the tabs using an index. The following methods and properties are
available:
removeTabAt, indexOfComponent, indexOfTab
SelectedIndex, ComponentAt, TitleAt, IconAt, DisabledIconAt, BackgroundAt, ForegroundAt,
EnabledAt.

SAP AG JA200 3-34
SAP AG 2003
JDesktopPane with
JInternalFrames
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JDesktop
Pane
JDesktopPane allows you to manage multiple windows
(JInternalFrame). This is known as Multiple Document
Interface (MDI).
Desktops with JDesktopPane and JInternalFrame
JLayered
Pane
A main window (JDesktopPane)
can contain any number of subscreens
(JInternalFrame).
JInternal
Frame



n It is common, especially in Windows, for programs to have a main window and arrange their
numerous, simultaneously opened subscreens within this main window (MDI, Multiple Document
Interface, for example in word processing, graphics programs, or development environments).
n In AWT, you cannot develop MDI applications, but it is quite straightforward in Swing. You merely
require the following components:
n Desktop
In principle, you can use any main window class as a desktop, but normally the JFrame class is used.
To manage the subscreens, the predefined ContentPane is replaced with an instance of the
JDesktopPane class, which has a DesktopManager that manages the subscreens
(increasing/decreasing size of subscreens, or moving them).
n Subscreens
The subscreens are derived from JInternalFrame. JInternalFrame is a derivation of the JComponent
class. The reason why JInternalFrame is not derived from JFrame is that, as a frame, JFrame always
has an operating system-specific window resource and is therefore unsuitable for use within another
window.

SAP AG JA200 3-35
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 3
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-36
SAP AG 2003
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JLabel
1 String set-/getText
2 Icon set-/getIcon
3 Icon set-/getDisabledIcon
4 char set-/getDisplayedMnemonic
5 int set-/get- Vertical-/HorizontalAlignment
6 int set-/get- Vertical-/HorizontalTextPosition
7 int set-/getIconTextGap
A JLabel represents a simple text/graphics display
Text
JLabel
TextPosition
Mnemonic
Alignment
JLabel



n With Swing 1.1.1 it is also possible to display HTML text in such a label.
n A JLabel is a dialog element used to display a (usually unchangeable) text. It can be used, for
example, to label another dialog component. In contrast with a java.awt.Label, a JLabel can contain
an additional icon.

Line 1: The text to be displayed in the label
Line 2: The icon to be displayed in the label. As an icon, use ImageIcon, for example. ImageIcon has a
constructor with which you must only pass the complete path for a specific graphic.
Line 3: The icon displayed for the state "enabled = false"
Line 4: With this feature you can underline a letter (see "Menus")
Line 5: Alignment of label content. The possible alignment values can be found in the
SwingConstants class:
Horizontal: LEFT, CENTER, RIGHT, LEADING, TRAILING
Vertical: TOP, CENTER, BOTTOM
Line 6: Alignment of the text displayed in the label
Line 7: Size of gap between text and icon

SAP AG JA200 3-37

SAP AG 2003
Text Components: Derivation Hierarchy
<<abstract>>
JTextComponent
JEditorPane
JTextArea
JTextField
JTextPane
JPasswordField
java. lang java. awt
Object
<<abstract>>
Componen
t
Container
javax .swing
JCompo
nent
<<Interface>>
Scrollabl
e
<<Interface>>
Scrollabl
e
javax .swing.text
Text editor (mixed fonts, colors, and so on)
Simple editor; allows fonts, colors, and so on
Abstract predecessor of all text components
Text editor for simple text (only one) style)
Text field single - line)
Password
field



n Text components
JTextField provides a text input box (single-line). The component can also be set so that it only
accepts specific formats (such as numeric formats).
JPasswordField is modified so that when you enter a password, every character is represented by a
so-called "echoChar (usually asterisk "*).
JTextArea displays simple, non-stylized text, but the output can be displayed with a specific font.
JEditorPane is powerful editor in its basic form, but is further enhanced by the derivation JTextPane.
Depending on the content, a different editor is used. Three types of content are already defined in
JEditorPane: text/plain, text/html, text/rtf.
JEditorPane can contain graphics.
JTextPane is intended for editing texts (word processing). Additional paragraphs are defined, which
can be assigned styles. As well as graphics, you can insert whole components (derivations of
java.awt.Component) into the text.

SAP AG JA200 3-38
SAP AG 2003
1 Caret set-/getCaret
2 Color set-/getCaretColor
3 int set-/getCaretPosition
4 Document set-/getDocument
5 Insets set-/getMargin
6 Color set-/getSelectedTextColor/SelectionColor
7 Color set-/getDisabledTextColor
8 int set-/getSelection-Start/End
9 String set-/getText
10 boolean set-/getEditable
11 boolean set-/getOpaque
JTextComponent
Abstract Class JTextComponent



Line 1: Placeholder in a document. A "caret" is the insertion marker that generally appears in text
fields to specify the cursor position or selection.
Line 2: Color of placeholder
Line 3: Position of placeholder
Line 4: Representation of processed document
Line 5: The size of the gap between the actual text area and the component. "Margin" refers to the
margin of the component around the necessary visible part.
Line 6: Color of selected text or its background.
Line 7: Color of text if the component is deactivated
Line 8: Start and end of text selection
Line 9: Text represented by the control. See also: "Document".
Line 10: Defines whether the component can be edited
Line 11: Defines whether the component is opaque (not transparent)

SAP AG JA200 3-39
SAP AG 2003
Abstract Class JTextComponent: MVC
<<abstract>>
JTextComponent
Document
View
Con-
troller
Model
Swing implements the Model View
Controller concept fully
In the case of a text component,
JTextComponent itself is the
controller
The data comes from a document
(model)
If you want to check whether the
input values for a component are
correct, use the relevant model class
for the component




SAP AG JA200 3-40
SAP AG 2003
javax.swing.text
Documents: Derivation Hierarchy
AbstractDocument
PlainDocument
DefaultStyledDocument
HTMLDocument
Text with style (writing and so on) and graphics
Interface: Representation of a document
Abstract class for representing a document
Default implementation of StyledDocument
Representation of an HTML document
Document
StyledDocument
Simple text document without style
javax.swing.event
Event data for DocumentListener
DocumentListener
Events: Change, insert, delete:
Methods changedUpdate, insertUpdate,
removeUpdate
DocumentEvent



n Documents
The data contained in the editor components (texts, documents) is functionally represented by the
Document interface. This interface defines methods to change the document contents or influence
the changes, and to retrieve the contents.
StyledDocument is a special derivation of Document intended for multistyle text.
The implementations of these interfaces are all derived from AbstractDocument.
Changes to documents trigger DocumentEvents in the model (document implementations), which
can be caught using a DocumentListener.

SAP AG JA200 3-41
SAP AG 2003
JPasswordField, JTextField, JLabel
1 char[] password = pwField.getPassword();
2 if (some.equals(+password))
3 // or
4 if (new String(password).equals(some)){ }
The following code shows how to check the
password:
JTextField
. . .
1 label = new JLabel();
2 JPasswordField pwField = new JPasswordField( 20 );
3 JTextField textField1 = new JTextField( 20 );
5 JPanel panel = new JPanel();
6 panel.add( pwField );
7 panel.add( textField1 );
9 panel.add( label );
. . .
JPasswordField
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
<<abstract>>
JText
Component
JTextField
JPass
wordField



Line 1: A JLabel is defined
Line 2: A JPasswordField is defined (displayed length: 20 characters)
Lines 3-4: JTextFields are defined (displayed length: 20 characters)
Lines 6-8: The fields are added to a panel

JPasswordField
A password field is easy to use, it is very similar to JTextField. You can suppress the output of the
password by setting a so-called echo character as char (method "setEchoChar()"). If you want to
display the password, set the value of this field to 0. To read the password, use the getPassword()
method. The above code shows two examples of how to create a string from the returned char array.

SAP AG JA200 3-42
SAP AG 2003
JTextField: Format Check
Changing the model class after the dialog component:
The JTextField class uses
javax.swing.text.PlainDocument as a model,
which means that all entries are passed on to the
model by the controller
To get an individual format check you must
derive your own class from PlainDocument,
override the insertString(...) or remove(...)
methods, and pass the new class to JTextField
as a model
Specifying the time of the check:
- After action (action-driven), for example ENTER
- After change (change-driven), for example pressing a key
JTextField
Document
View
Con-
troller
Model
<<abstract>>
JTextComponent
PlainDocument
MyDocument



n Format check
The following describes how to execute a format check for a JTextField.

Step 1:
Decide when the format check is to take place (for example, after pressing the Enter key or already
during the input).
Implement appropriate listener classes (if necessary).

Step 2:
Change the model class after the view. Changes to documents are made using the insertString and
remove methods (defined in Document). In the case of JTextField, this text input component works
with PlainDocument as the model. Now derive your own class from PlainDocument and override
the relevant methods. This prevents any insertion or removal of characters if this would destroy the
format.

SAP AG JA200 3-43
SAP AG 2003
JTextField: Format Check (2)
The java.text package already provides classes with which you can
execute the format check
Executing the check
SimpleDateFormat
<<abstract>>
Format
<<abstract>>
DateFormat
<<abstract>>
NumberFormat
ChoiceFormat
DecimalFormat
<<Own derivation>>
java.text



n Step 2:
To execute the check, you can hold an instance of a Format class within your Document
implementation (package java.text) and check the new text with the parseObject function in the case
of any changes.
The Format class and derivations were covered in the course "JA100 StartUp Kit" in the context of
the subject "Internationalization. It is important to note that, as an abstract class, the NumberFormat
class returns objects of its own derivation using the following static methods:
getNumberInstance: Simple numeric formatting
getPercentInstance: Converts "0,8 to "80%, for example
getCurrencyInstance: Currency format, for example "-824,35 DM. The output can vary
depending on the overloaded method used and the language setting on the target computer.
Therefore, when using this format, you should always ensure that the correct currency is set for the
displayed amount.

SAP AG JA200 3-44
SAP AG 2003
Inserting a character in textField
raises an exception
JTextField: Format Check (3)
. . .
1 Document doc = new IntegerDocument();
2 JTextField textField = new JTextField( 20 );
3 textField.setDocument( doc );
. . .
4 private class IntegerDocument extends PlainDocument {
5 private NumberFormat nrFormat;
6 public IntegerDocument() {
7 this.nrFormat = NumberFormat.getNumberInstance();
8 }
9 public void insertString( int offs, String str, AttributeSet a )
10 throws BadLocationException
11 {
12 try {
13 nrFormat.parseObject(str);
14 super.insertString(offs, str, a);
15 } catch (ParseException e) {
16 label.setText("IntegerDocument: not a valid value: " + str);
17 }
18 }
19 } // inner class
. . .
Demo



Line 1: An instance of the (internal) class IntegerDocument is created (see lines 4-19)
Line 2: A JTextField is instantiated
Line 3: The JTextField is passed the created object of the class IntegerDocument as a model. All
changes to the dialog component are now passed directly to this model class by the
controller.
Lines 4-19: The internal class IntegerDocument is derived from the PlainDocument class and works
internally with an instance of the NumberFormat class
Line 9: The insertString method is overridden so that the inserted text is first parsed by the
NumberFormat class. If a ParseException is raised, the text is not inserted in the
document. If no error occurs, the relevant method of the parent class is called (here,
super.insertString, line 14).

SAP AG JA200 3-45
SAP AG 2003
JTextArea
JTextArea is a component for displaying and entering multiline,
unformatted texts
The texts can contain line breaks and tabs, but not different fonts,
colors, or graphical elements
JTextArea within
a JDialog
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JTextArea
<<abstract>>
JText
Component



n JTextArea
JTextArea is unable to scroll text automatically if it is too long or too wide for the available screen
section. To get around this you must embed the text field in a component of the type JScrollPane.
Instead of JTextArea, you must then add JScrollPane to the dialog.

JTextArea contains both a controller, to enable and control data input, and a view, that is the display.
In the case of JTextArea, the model is an object of the PlainDocument class by default; this object
implements the Document interface. JTextArea itself works with this interface Document.

SAP AG JA200 3-46
SAP AG 2003
1 boolean set-/getLineWrap
2 boolean set-/getWrapStyleWord
3 int getLineCount
4 int getLineOfOffset(int offset)
5 int getLineStartOffset(int line)
/ getLineEndOffset (int line)
6 void insert(String str, int pos)
7 void replaceRange(String str, int start, int end)
JTextArea
JTextArea (2)



Line 1: Defines whether a line break should take place. Default: false
Line 2: Defines whether a line break can take place in a word. Default: true
Line 3: Number of lines in the input box
Line 4: Number of the line that contains the character with the position offset
Line 5: Number of characters at which the line starts/ends
Line 6: Inserts the string str at the position pos
Line 7: Replaces the string between start and end with str

SAP AG JA200 3-47
SAP AG 2003
JEditorPane, JTextPane
JEditorPane is a component for displaying and entering multiline,
formatted texts
JEditorPane within a JDialog
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JEditor
Pane
JText
Pane
<<abstract>>
JText
Component



JEditorPane
Objects of the class JEditorPane can be used to display multiline texts. Depending on the type of
content, the class automatically uses the following editors to display the content:
text/plain: javax.swing.text.DefaultEditorKit
text/html: javax.swing.text.html.HTMLEditorKit
text/rtf: javax.swing.text.rtf.RTFEditorKit

JTextPane
The class JTextPane is derived from JEditorPane. By default, it uses an object of the class
javax.swing.text.StyledEditorKit as a controller. Using this class, data (text) is passed from the view to
the model. Functions, such as overriding and so on, are supported.
The model itself is of the type javax.swing.text.DefaultStyledDocument, which implements the
interface javax.swing.text.StyledDocument.

SAP AG JA200 3-48
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 4
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-49
SAP AG 2003
Derivation Hierarchy
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
<<abstract>>
JAbstract
Button
JCompo
nent
JButton JToggleButton JMenuItem
JCheckBoxMenuItem JRadioButtonMenuItem
JCheckBox JRadioButton



n In JFC, the menu input elements (XXXMenuItem) are treated like buttons and are derived from the
AbstractButton class. You can also derive your own buttons from this class. If you wish to create a
switch, you are better to use JToggleButton.

AbstractButton: Abstract predecessor of all buttons
JMenuItem: Simple menu entry
JCheckBoxMenuItem: Menu entry as a CheckBox
JRadioButtonMenuItem: Menu entry as a RadioButton
JButton: Simple button
JToggleButton: Predecessor of all switches
JCheckBox: CheckBox
JRadioButton: RadioButton



SAP AG JA200 3-50
SAP AG 2003
Menus
Objects of the JFrame class and its subclasses can contain
a menu system through which the users can control
processing
All parts of the menu system are implemented through
special classes, whose objects have to be combined
Main screen of example application
"CarControlApp" with menu
JMenuBar JMenu JMenuItem
JRadioButtonMenuItem
JCheckBoxMenuItem
JSeparator
JPopupMenu



n Menus
Using menu bars allows the user to interact with the program. The user can choose menu options and
hence implicitly trigger events that the program must react to.
n To create a complete menu you first require a JMenuBar component. You can add it to a JFrame
using the method setJMenuBar(JMenuBar).
n The individual main menus are represented by JMenu objects and can be added using the add
function of JMenuBar.
n The subitems of a main menu can be of different types: A simple menu option: JMenuItem; a
separator: JSeparator; a check box menu option: JCheckBoxMenuItem; a radio button menu option:
JRadioButtonMenuItem.
n In the case of a JRadioButtonMenuItem, note that you must add it to a ButtonGroup object. This
object logically combines different selection fields into groups, so that they can be separated.

SAP AG JA200 3-51
SAP AG 2003
JMenuBar, JMenu
JMenu JMenuBar
. . .
1 JFrame frame = new JFrame();
2 JMenuBar menuBar = new JMenuBar();
3 JMenu menuFile = new JMenu("File");
4 JMenu menuTools = new JMenu("File");
5 JMenu menuHelp = new JMenu("File");
6 menuBar.add( menuFile );
7 menuBar.add( menuTools );
8 menuBar.add( menuHelp );
9 frame.setJMenuBar( menuBar );
. . .
Demo
A menu bar represents the main menu of a window
The parts of a menu bar are the individual menus



Line 1: Creates a JFrame object
Line 2: Creates a JMenuBar object
Lines 3-5: Create the individual JMenuItems
Lines 6-8: The JMenuItems are added to the JMenuBar
Line 9: The JMenuBar is added to the JFrame

SAP AG JA200 3-52
SAP AG 2003
JMenuItem
The menu items form the elementary parts of a menu
JMenuItem
JSeparator
. . .
1 JMenu menuHelp = new JMenu("Help");
2 menuHelp.setMnemonic('H');
3 JMenuItem mItemHelp = new JMenuItem("Help Topics");
4 mItemHelp.setActionCommand( "Help" );
5 mItemHelp.addActionListener( new MenuItemAction(this));
6 JMenuItem mItemAbout = new JMenuItem("About");
7 mItemAbout.setActionCommand( "About" );
8 mItemAbout.addActionListener( new MenuItemAction(this) );
9 menuHelp.add( mItemHelp );
10 menuHelp.add( new JSeparator() );
11 menuHelp.add( mItemAbout );
. . .
Demo



Line 1: Creates a JMenu object
Line 2: To add a so-called mnemonic (underlining of individual letters) use the setMnemonic
method It can be called with string as well as other arguments (see API documentation).
Line 3: Creates a JMenuItem object
Lines 4-5: An ActionCommand and an EventListener are added to the JMenuItem object
Lines 6-8: Another JMenuItem object is created
Lines 9-11: The JMenuItems are added to the JMenu. They are separated by a separator
(JSeparator). By using JSeparator, you can optically separate different items from one
another.

SAP AG JA200 3-53
SAP AG 2003
JRadioButtonMenuItem, JCheckBoxMenuItem
. . .
1 JMenu menuTools = new JMenu("Tools");
2 JMenu mn_LF = new JMenu("Look and Feel");
3 ButtonGroup btnGroup_LF = new ButtonGroup();
4 jRadio_LF_Motif = new JRadioButtonMenuItem("Motif");
5 jRadio_LF_Motif.setActionCommand( "LF_Motif" );
6 jRadio_LF_Motif.addActionListener( new MenuItemAction(this) );
7 jRadio_LF_Win = new JRadioButtonMenuItem("Windows");
8 jRadio_LF_Win.setActionCommand( "LF_Windows" );
9 jRadio_LF_Win.addActionListener( new MenuItemAction(this) );
10 jRadio_LF_Metal = new JRadioButtonMenuItem("Metal");
11 jRadio_LF_Metal.setActionCommand( "LF_Metal" );
12 jRadio_LF_Metal.addActionListener( new MenuItemAction(this) );
13 btnGroup_LF.add(jRadio_LF_Motif);
14 btnGroup_LF.add(jRadio_LF_Win);
15 btnGroup_LF.add(jRadio_LF_Metal);
16 mn_LF.add(jRadio_LF_Motif);
17 mn_LF.add(jRadio_LF_Win);
18 mn_LF.add(jRadio_LF_Metal);
19 mn_Check=new JCheckBoxMenuItem( "on" );
20 menuTools.add(mn_LF);
21 menuTools.add(mn_Check);
. . .
JRadioButtonMenuItem
JCheckBoxMenuItem
The menu items form the elementary parts of a menu
Demo



Line 1: Creates a JMenu object
Line 2: Creates a JMenuItem object
Line 3: If you want a choice between different items with radio buttons, you have to create a
button group instance for each selection. You can then simply add instances of
JRadioButtonMenuItem to this ButtonGroup instance or to a menu (lines 13-15).
Lines 5-6: An ActionCommand and an EventListener are added to the JRadioButtonMenuItem
object
Lines 6-12: Additional JRadioButtonMenuItem objects are created
Lines 13-15:The instances of the JRadioButtonMenuItem are added to the ButtonGroup instance
Lines 16-18:The instances of the JRadioButtonMenuItem are added to the JMenu
Line 19: Use the JCheckBoxMenuItem class to create a check box, which can be added to JMenu using
add, just like JMenuItem
Lines 19-20: The instances of the submenu "Look and Feel" and the CheckBox are added to the
"Tools" menu

SAP AG JA200 3-54
SAP AG 2003
JPopupMenu
1 JPanel panel = new JPanel();
2 panel.addMouseListener(new LocalPopUpMenuAction());
3 JFrame frame = new JFrame();
4 frame.getContentPane().add( panel );
5 private void initializePopUpMenu() {
6 jPopupMenu = new JPopupMenu();
7 JMenuItem jMenuItem1 = new JMenuItem("This is");
8 JMenuItem jMenuItem2 = new JMenuItem("a simple");
5 JMenuItem jMenuItem3 = new JMenuItem("test");
10 jPopupMenu.add(jMenuItem1);
11 jPopupMenu.add(jMenuItem2)
12 jPopupMenu.add(jMenuItem3);
13 }
14 public class LocalPopUpMenuAction extends MouseAdapter {
15 public void mouseReleased(MouseEvent e){
16 jPopupMenu.show(e.getComponent(),
e.getX(), e.getY());
17 }
18 }
JPopupMenu
Demo



Line 6: A PopupMenu is created using the relevant class JPopupMenu. As with JMenu, you can fill it
with submenu items.
Lines 2, 14: However, you must trigger the popup display yourself. In Windows, popup menus are
usually displayed by clicking the right mouse button. To do this, you must respond to the
event mouseReleased. The simplest way to do this is to implement the MouseListener
interface.
Line 2: Your class/object must then be registered with the screen element for which there is to be
a popup. In this case, the element is jPanel, registration is carried out using
addMouseListener.
Line 16: Use the show function to display the popup.
The parameters are as follows:
A component object, the X coordinate at which the popup is to be displayed, and the Y
coordinate at which the popup is to be displayed.

SAP AG JA200 3-55
SAP AG 2003
Menu Events
1 //...
2 jMenuItem.addActionListener(this);
3 jCheckBoxMenuItem.addItemListener(this);
4 //...
1 public void actionPerformed(ActionEvent e) {
2 //...
3 }
4 public void itemStateChanged(ItemEvent e) {
5 //...
6 }
Registration
Reaction
Event control
All submenus:
Interface ActionListener, method actionPerformed
JRadioButtonMenuItem, JCheckBoxMenuItem:
Interface ItemListener, method itemStateChanged




SAP AG JA200 3-56
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 5
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-57
SAP AG 2003
Buttons
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
<<abstract>>
JAbstract
Button
JCompo
nent
JButton JToggleButton JMenuItem
JCheckBoxMenuItem JRadioButtonMenuItem
JCheckBox JRadioButton



n In JFC, the menu input elements (XXXMenuItem) are treated like buttons and are derived from the
AbstractButton class. You can also derive your own buttons from this class. If you wish to create a
switch, you are advised to use JToggleButton.
AbstractButton: Abstract predecessor of all buttons
JMenuItem: Simple menu entry
JCheckBoxMenuItem: Menu entry as a CheckBox
JRadioButtonMenuItem: Menu entry as a RadioButton
JButton: Simple button
JToggleButton: Predecessor of all switches
JCheckBox: CheckBox
JRadioButton: RadioButton


SAP AG JA200 3-58
SAP AG 2003
JButton
. . .
1 JButton button1 = new JButton("ok");
2 JButton button2 = new JButton("cancel");
3 JButton button3 = new JButton();
4 button3.setBorderPainted(false);
5 ImageIcon iconInitial = new ImageIcon(x1,gif);
6 ImageIcon iconSelected = new ImageIcon(x2,gif);
7 button3.setIcon(iconInitial);
8 button3.setActionCommand( "zoomIn" );
9 button3.setToolTipText( "Show information" );
10 button3.addActionListener( new LocalActionListener() );
11 button3.addMouseListener( new LocalMouseListener( button3, iconSelected ));
12 JButton button4 = new JButton();
13 button4.setRolloverEnabled(true);
14 button4.setIcon( iconInitial );
15 button4.setRolloverIcon( iconSelected );
16 JPanel panel = new JPanel();
17 JPanel.setLayout( new FlowLayout() );
18 panel.add( button1 );
. . .
Show information
Demo



The standard button JButton allows you to display buttons in a variety of different ways.
Lines 1-3: Defines three buttons. You can set or read text and graphics using the text (type:
String) and icon (type: icon) properties.
Line 4: Button 3 is assigned an icon but no border.
Line 7: Assigns an icon to the button. As well as the standard image property icon, you can
choose different images for different button states - that is, up (not pressed), disabled,
pressed, rollover (mouse cursor over button), selected, rolloverSelected (mouse cursor
over button and selected), selectedDisabled (selected but inactive).
Line 9: The tool tips are visible as soon as the cursor moves over the button.
Line 10: Adds an ActionListener to the button.
Line 11: Adds a MouseListener to the button, which allows the button to react to mouse
movements. For example, the icon can change whenever the cursor moves over the
button.
Lines 14-15: You can switch the rollover effect on and off using the boolean type property of the
same name.

SAP AG JA200 3-59
SAP AG 2003
JCheckBox
Main feature not available with JButton: The Selected
property
JCheckBox
Event handling
Interface ItemListener, method itemStateChanged
. . .
1 JCheckBox checkBox = new JCheckBox( "not selected" );
2 checkBox.addItemListener( new LocalItemListener() );
3 panel.add( checkBox );
4 private class LocalItemListener implements ItemListener {
5 public void itemStateChanged( ItemEvent event ) {
6 JCheckBox checkbox = (JCheckBox)event.getSource();
7 if( event.getStateChange() == event.SELECTED ) {
8 checkbox.setText("selected");
9 } else {
10 checkbox.setText("not selected");
11 }
12 }
13 }
. . .
JCheckBox
Demo



A JCheckbox is a simple switch button derived from JToggleButton.
The main advantage of JCheckBox over JButton is the Selected property implemented above. Another
difference is that the button state (selected/not selected) is changed using the itemStateChanged method
of the itemListener interface.

Line 1: A checkbox is defined
Line 2: An ItemListener is added to the checkbox.
Lines 7-11: The ItemListener reacts to the user selecting the checkbox.

SAP AG JA200 3-60
SAP AG 2003
JRadioButton
Main difference between JRadioButton and JCheckBox:
You must group radio buttons using ButtonGroups.
JRadioButton
JRadioButton
Event handling
Interface ActionListener, method actionPerformed
. . .
1 ButtonGroup btnGroup = new ButtonGroup();
2 JRadioButton jRadioBtn1 = new JRadioButton( "yellow" );
3 jRadioBtn1.setActionCommand( "yellow" );
4 jRadioBtn1.addActionListener( new LocalActionListener() );
5 btnGroup.add(jRadioBtn1);
6 panel.add( jRadioBtn1 );
7 private class LocalActionListener implements ActionListener {
8 public void actionPerformed( ActionEvent event) {
9 JRadioButton jrb = (JRadioButton)event.getSource();
10 if (event.getActionCommand().equals("yellow")) {
11 jrb.setBackground( Color.yellow );
12 }
13 }
14 }
. . .
Demo



A JRadioButton allows users to select from a predefined set of values.
To separate different sets of values (that is, selection groups), create a ButtonGroup object instance for
each group and then include the buttons you want in it using the add method.

Line 1: A ButtonGroup is defined
Line 2-4: A JRadioButton is defined and an ActionListener is assigned to it (among other elements).
Line 5: The JRadioButton is added to the ButtonGroup.
Line 6: The JRadioButton is also added to the panel. You can then define other JRadioButtons
and add them to the ButtonGroup or panel. For reasons of space, these other buttons are
not shown in the above example.
Line 7: The ActionListener reacts when the user selects the appropriate JRadioButton. Only one
JRadioButton in the ButtonGroup can be selected at any one time.

SAP AG JA200 3-61
SAP AG 2003
Graphic: Dialog box with a
JComboBox from the
"CarControlApp" application
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JCombo
Box
JComboBox is a combination of a text field and a list
The user opens the list only if he or she wants to select a value from it
The JComboBox allows single selection only
JComboBox
JComboBox



n The JComboBox (or drop-down list) component works with all classes. This means that you can
display objects other than String objects in the ComboBox.
n However, only two display forms are delivered with Swing - one for the String classes, and one for
the classes that implement the Icon interface.
n To use your own display forms, you need to write a ListCellRenderer. This is also the name of the
interface that you implement with a new class.
n Your new class should be a subclass of JLabel. In the getListCellRendererComponent method,
you return an object of this class using "return this;". The JComboBox then calls its paint()
method.

SAP AG JA200 3-62
SAP AG 2003
JComboBox (2)
1 public void addItem(Object anObject);
2 insertItemAt(Object anObject, int index);
3 public Object getItemAt(int index);
4 public void removeAllItems();
5 public void removeItemAt(int index);
6 public void removeItem(Object object);
7 public void insertItemAt(Object object, int index);
8 int getItemCount
9 int get-/setSelectedIndex
10 Object get-/setSelectedItem
JComboBox



Line 1: Adds a new element (string or icon) to the list.
Line 2: Adds a new element at the index position.
Line 3: Returns the element at the index position.
Line 4: Number of elements in the list.
Line 5: Index of the object currently selected in the list.
Line 6: Removes the specified object from the list.
Line 7: Inserts an object at the specified position.
Line 8: Number of elements in the list.
Line 9: Index of the object currently selected in the list.
Line 10: The currently selected object in the list.

SAP AG JA200 3-63
SAP AG 2003
JComboBox (3)
Event handling
Interface ActionListener, method actionPerformed
1 JComboBox someList = new JComboBox();
2 someList.addItem(erstes Element);
3 someList.addItem(zweites Element);
4 someList.addActionListener ( new ActionListener(){
5 public void actionPerformed(ActionEvent e){
6 String chosenValue = (String)someList.getSelectedItem();
7 System.out.println(chosenValue);
8 }
9 }



n Whenver another element is selected, the JComboBox sends an ItemEvent to registered ItemListener
(for both the deselected and selected element). After the user has finished selecting the item, or has
manually entered a value in an editable JComboBox, an ActionEvent is sent to registered
ActionListeners.

SAP AG JA200 3-64
SAP AG 2003
Graphic: Dialog box with a JList from
the "CarControlApp" application
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo
nent
JList
A JList displays a single-column set of values; users can select one
or more entries from the set
You can display any object in a JList, not just strings
JList
JList



n JList
JList can contain only one column. That is, JList programming in Swing is not to be confused with
list programming in ABAP.
List JTextArea and other components, JList does not have any data scrolling functions when the data
does not fit the screen. However, you can insert a JList in a JScrollPane before you add it to a GUI
container.

SAP AG JA200 3-65
SAP AG 2003
JList: MVC (1)
JList
View
Con-
troller
Model
ListSelectionModel
Model
DefaultList
SelectionModel
JList uses the model interface ListSelectionModel
for selection and the model interface ListModel
for data
ListModel
DefaultListModel
1 ListModel set-/getModel
2 ListSelectionModel set-/getSelectionModel



n Line 1: Use these methods to access the JList data model.
Line 2: Use these methods to access the selection model used by the list. You do not need to use this
model, since all the methods you need are defined in the class JList itself. These methods will be
covered in more detail later.

SAP AG JA200 3-66
SAP AG 2003
JList: MVC (2)
JList
View
Con-
troller
Model
ListModel
1 String[] myValues = {red, blue, yellow}
2 JList myList1 = new JList(myValues);
You can use the JList constructor to have a data model class
(default implementation) created for you
If you have created a JList with an automatically
generated list model, you can no longer add or
change values
DefaultListModel



n Creating a ListModel using the constructor
You can create a data model class with a default implementation using the constructor. That is, you
do not have to work with the model implementations directly. To do this, you pass a list of objects
(strings, images) in the constructor, either as an object array or a vector.

JList(Object[] listData) bzw. JList(Vector listData)

If you pass an array or Vector, JList creates a list model from the data and uses it for display. You
can also define the content of the list by passing an instance of the ListModel class directly.

SAP AG JA200 3-67
SAP AG 2003
JList: MVC (3), ListModel
JList
View
Con-
troller
Model
ListModel
1 String[] myValues = {red, blue, yellow}
2 JList myList2 =
new JList(new DefaultListModel(myValues));
3 DefaultListModel dlm =
DefaultListModel)myList2.getModel();
4 dlm.add(black);
If you want to change the contents of a JList after it has been
generated, use either the DefaultListModel or create your own
ListModel
Each of the models has two default
implementations (DefaultListSelectionModel
and DefaultListModel)
DefaultListModel



n If you want to change the content of a JList after its instance has been created, you must create a
model yourself - you cannot use the automatically generated list model.
All JList models must implement the ListModel interface and notify registered listeners each time
the data changes by emitting a ListDataEvent. The DefaultListModel class offers an implementation
that is suitable for most purposes.

SAP AG JA200 3-68
SAP AG 2003
JList: MVC (4), ListSelectionModel
JList
View
Con-
troller
Model
ListSelectionModel
DefaultList
SelectionModel
The ListSelectionModel organizes the currently active selection
It triggers events if the selection changes
The DefaultListSelectionModel is most
commonly used
The get-/setSelectionMode methods define how many elements
the user can select:
MULTIPLE_INTERVAL_SELECTION
SINGLE_INTERVAL_SELECTION
SINGLE_SELECTION



n If you want to change the content of a JList after its instance has been created, you must create a
model yourself - you cannot use the automatically generated list model.
All JList models must implement the ListModel interface and notify registered listeners each time
the data changes by emitting a ListDataEvent. The DefaultListModel class offers an implementation
that is suitable for most purposes.

SAP AG JA200 3-69
SAP AG 2003
JList: Simple Selection Example
There is no standard event for a double-click on an element
1 String[] myValues = {red, blue, yellow}
2 JList myList = new JList(new DefaultListModel(myValues));
3 MouseListener myMouseListener = new MouseAdapter() {
4 public void mouseClicked(MouseEvent e) {
5 if (e.getClickCount() == 2) {
6 int index = myList.locationToIndex(e.getPoint());
7 System.out.println(Click on element no.:" + index);
8 }
9 }
10 };
11 myList.addMouseListener(MyMouseListener);
1 String[] myValues = {red, blue, yellow}
2 JList myList = new JList(new DefaultListModel(myValues));
3 myList.setSelectedValue(red, true);
4 myList.getSelectionModel().addListSelectionListener(this);
5 public void valueChanged(ListSelectionEvent e){
6 System.out.println(myList.getSelectedValue());
7 }



Line 1-2: First, the example shows the initialization section discussed previously.
Line 3: A value, which must be defined in the list, is selected. You could also have made this
selection directly using the SelectionModel (although this is more complicated):
myList.getSelectionModel().setLeadSelectionIndex(0);
However, this statement cannot guarantee that the element with the index value 0
("red") is also visible to the user, unlike setSelectedValue. The next few lines of code
specify how the program reacts to selection events using the ListSelectionModel.

SAP AG JA200 3-70
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Container Swing properties
Swing Overview 6
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-71
SAP AG 2003
Graphic: JFileChooser
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo-
nent
JFile-
Chooser
Choosing files or folders
Modes: Open, Save, Custom
Filters can be used: Several options
File preview possible: Override the FileView class
Inclusion with other components possible
Immediate reaction to changing selection possible
JFileChooser



n JDialog enables you to use a window as a modal (locking) window. This means that all entries or
mouse clicks in other windows are ignored and the modal window is always displayed on top.
n To set a a dialog to modal you can either use the relevant constructor of the JDialog class or call the
setModal(..) method.

SAP AG JA200 3-72
SAP AG 2003
JFileChooser (2): Important Methods
JFileChooser
1 int showOpenDialog(Component parent)
2 int showSaveDialog(Component parent)
3 int showDialog(Component parent, String approveButtonText)
4 boolean set-/getMultiSelectionEnabled
5 int set-/getFileSelectionMode
6 boolean getDirectorySelectionEnabled
7 boolean getFileSelectionEnabled
8 File set-/getCurrentDirectory
9 void ensureFileIsVisible(File f)
10 void changeToParentDirectory()
11 void rescanCurrentDirectory()
In the JFileChooser class, the following methods are defined
(among others):
APPROVE_OPTION: User has chosen appropriately
CANCEL_OPTION: Selection canceled by user
FILES_ONLY
DIRECTORIES_ONLY
FILES_AND_DIRECTORIES



Line 1: Provides a standard dialog for opening files or folders
Line 2: Provides a standard dialog for saving files or folders
Line 3: Allows you to define your own functions for dialogs. To do this, you specify the parent
component and a string that will appear on the OK button in the dialog box.
Line 4: Specifies whether the user can select more than one file or folder.
Line 5: Specifies whether the user can select files, folders, or both. Lines 6 and 7 allow you to
query the current setting but not change it.
Line 8: Specifies or returns the currently displayed folder.
Line 9: If necessary, scrolls to the specified file, so that it is visible on the screen.
Line 10: Changes to the folder immediately above the current one.
Line 11: Refreshes the display of the current folder.

SAP AG JA200 3-73
SAP AG 2003
Graphic: JColorChooser
JFileChooser (3): Creating Your Own Filters
3 import java.io.*;
4 public class EasyFileFilter extends javax.swing.filechooser.FileFilter {
5 public boolean accept(File f){
6 if ((!f.isDirectory())&&f.getName().endsWith(.txt)) {
7 return true;
8 }
9 return false;
10 }
11
11 public String getDescription(){
12 return JA200 Filter (*.txt);
13 }
14 }
1 JFileChooser fc = new JFileChooser();
2 fc.setFileFilter(new EasyFileFilter());
Demo



n As well as the ChoosableFileFilters property, you can also change the list of FileFilters that the
user can select, using the following methods:
void addChoosableFileFilter(FileFilter f): Adds a FileFilter
boolean removeChoosableFileFilter(FileFilter f): Removes a FileFilter
void resetChoosableFileFilters(): Resets the list to its initial state
n In this case, we are using an instance of the FileFilter class in the javax.swing. filechooser package,
not the FileFilter interface. As well as an accept method, this class offers a Description property
(type: String), which you can use to set the title of the file format in the above dialog (here: ".txt").

SAP AG JA200 3-74
SAP AG 2003
JColorChooser
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo-
nent
JColor-
Chooser
JColorChooser
With this dialog, you can choose colors in three different
dialogs
You can choose between predefined colors, HSB values, and
RGB values
. . .
1 Component comp = (Component)event.getSource();
2 Color newColor = JColorChooser.showDialog(null, "Choose a color",
comp.getBackground() );
3 comp.setBackground( newColor );
. . .
Demo



Line 2: To display the color selection dialog on the screen, it is sufficient to call
JColorChooser.showDialog() with three arguments: A component object on which you can
paint, the dialog name, and an initial color.

If the user exits the dialog, the selected color is provided as the return value.
If the dialog is cancelled, the return value is zero.

SAP AG JA200 3-75
SAP AG 2003
java.lang java.awt
Object
<<abstract>>
Component
Container
javax.swing
JCompo-
nent
JOption-
Pane
JOptionPane
Simple dialog
Supports buttons, icons, messages, and
input
Icon
Message
JComboBox
(optional)
Buttons
JOptionPane



n JOptionPane
You can use the JOptionPane class to create Swing dialogs. In a single call of a static method, you
can create simple dialogs that contain only an icon and a text or input field, plus a choice of the
buttons "Yes", "No", and "Cancel".

SAP AG JA200 3-76
SAP AG 2003
JOptionPane (2)
Important methods and dialogs:
public static void showMessageDialog(
Component parent, Object message,
[, String title [, int msgType[, Icon icon ]]] );
public static int showConfirmDialog(
Component parentComponent, Object message,
[, String title [, int optionType [, int msgType[, Icon icon ]]]] );
public static Object showInputDialog( )
1 String[] lang = { "German", "English", "French" };
2 JOptionPane.showInputDialog( new JFrame(), "Please choose a language
,"JOptionPane, JOptionPane.QUESTION_MESSAGE
,null,lang, lang[2]);



n JOptionPane, ShowXXXDialog methods
JOptionPane offers several methods for controlling the appearance and behavior of the dialog.

The parameters have the following meaning:
Component parent Parent component, such as JFrame

Object message Message area, options:
- String Text message
- Component User component (bound)
- Icon Icon (displayed in label)

int messageType Kind of dialog:
- ERROR_MESSAGE
- INFORMATION_MESSAGE
- QUESTION_MESSAGE
- PLAIN_MESSAGE Message without icon or similar features

Int optionType Specifies button selection
- DEFAULT_OPTION;, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION
Icon icon Icon to be displayed on left of dialog. You can also use a default icon
(parameter messageType)
String title Dialog box title

SAP AG JA200 3-77
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 7
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-78
SAP AG 2003
The JTable API
The JTable class allows users to display, edit, and navigate
through data in a multi-row, multi-column format
JTable
javax.swing javax.swing.table
<<Interface>>
ListSelection
Model
<<Interface>>
ListSelection
Model
<<Interface>>
TableColumn
Model
<<Interface>>
TableColumn
Model
This package contains other interfaces and classes.
<<Interface>>
TableModel
<<Interface>>
TableModel
In JTable, data and display are separated (Model View Controller
pattern). The view and controller are part of the JTable class
(Delegate); the data in the model is described using interfaces
Delegate
View
Con-
troller
Model



n JTable class constructors
You use the JTable class to display data in two-dimensional tables. When you create instances of
JTable, you can make use predefined classes offering a range of functions - allowing users to change
the column width, navigate using tab keys, and select columns or rows. You can also use your own
classes to generate JTable instances and adapt the display of the table to your own needs.

SAP AG JA200 3-79
SAP AG 2003
Creating Instances of JTable
JTable offers several constructors:
JTable
1 public JTable()
2 public JTable(int numRows, int numColumns)
3 public JTable(Object[][] rowData, Object[] columnNames)
4 public JTable(Vector rowData, Vector columnNames)
5 public JTable(TableModel tm)
6 public JTable(TableModel tm, TableColumnModel tcm)
7 public JTable(TableModel tm, TableColumnModel tcm, ListSelectionModel lsm)
1 public class TestTable extends JFrame {
2 private Object tableData[][] =
{ {"VW", "New Beetle", new Integer(20425)},
{"Ford", "Transit", new Integer(354590)},
{"Audi", "A2", new Integer(3572)} };
3 private String columnNames[] =
{"Make", "Model", "Mileage"};
4 private JTable table;
5 public TestTable() {
table =
new JTable(tableData, columnNames);
6 // . . .



n JTable class constructors:
You can create object instances of this class using one of several constructors:
Line 1: Creates a default JTable using a default data model, default column model, and
default selection model.
Line 2: Creates a JTable with a given number of empty rows (numRows) and columns
(numColumns), using the DefaultTableModel.
Line 3: This constructor expects two arguments, the first of which contains the data you want
to display as a two-dimensional array. The first dimension contains the rows, the second the
columns. To display the table, the array elements are converted to strings internally using the
toString() method. The second argument contains the column headers in a string array.
Line 4: This constructor expects the data and column headers in vectors, such that the data
vector rowData contains a subvector with the data elements for each row.
Lines 5-7: These constructors each expect 1-3 explicitly declared models as arguments.
The TableModel provides the data; the TableColumnModel defines the columns; the
ListSelectionModel is responsible for how users select table elements. If all three models are
instantiated and passed (line 7), the program has complete control over how tables are displayed and
edited.

SAP AG JA200 3-80
SAP AG 2003
Configuring Instances of JTable
Use the following methods:
JTable
1 public void setRowHeight(int newHeight)
2 public void setRowMargin(int rowMargin)
3 public void setIntercellSpacing(Dimension newSpacing)
4 public void setShowGrid(boolean b)
5 public void setShowHorizontalLines(boolean b)
6 public void setShowVerticalLines(boolean b)
7 public void setAutoResizeMode(int mode)



n Configuring a JTable
Line 1: Specifies the height of a row; all rows are the same height.
Line 2: Specifies the blank space at the top and bottom of each cell.
The program calculates the space available for the cell's contents by subtracting this top
and bottom margin from the cell height.
Line 3: Specifies the horizontal (and vertical) margins for each cell element.
Line 4: Changes the border color.
Line 5-6: Specifies the foreground and background color for the selected area.
Line 7: Specifies the behavior of the table after the width of a column has been changed. You
can allocate the space freed up to (or specify the space taken from) the other columns as
follows (using parameter mode):
AUTO_RESIZE_OFF: Other columns are not resized.
AUTO_RESIZE_LAST_COLUMN: Uses the last column to adjust the size of the
other columns.
AUTO_RESIZE_NEXT_COLUMN: Uses the column immediately to the right of the modified
column to adjust the size of the other columns.
AUTO_RESIZE_SUBSEQUENT_COLUMNS: Distributes the space freed up or taken
equally to all columns to the right of the modified column.
AUTO_RESIZE_ALL_COLUMNS: Distributes the space freed up or taken to all the
other columns.

SAP AG JA200 3-81
SAP AG 2003
Editing JTable Elements
Use these methods to select JTable elements:
JTable
1 public void setRowSelectionAllowed(boolean flag)
2 public void setColumnSelectionAllowed(boolean flag)
3 public void setSelectionMode(int selectionMode)
4 public void setCellSelectionEnabled(boolean flag)
5 public int getSelectedRow()
6 public int getSelectedColumn()
7 public int[] getSelectedRows()
8 public int[] getSelectedColumns()
9 public void selectAll()
10 public void clearSelection()
11 public int getRowCount()
12 public int getColumnCount()
13 public Object getValueAt(int row, int column)
Use these methods to access elements:



n Configuring a JTable
Lines 1-2: If flag == true, users can select a row or column respectively.
Line 3: Specifies whether users can select a single element, a single contiguous range of elements,
or several different ranges. To do this, use the constants SINGLE_SELECTION,
SINGLE_INTERVAL_SELECTION, and MULTIPLE_INTERVAL_SELECTION or the
ListSelectionModel class.
Line 4: Allows the user to select a single rectangular area containing several cells (in different
rows and columns.
Lines 5-6: Returns the selected row or column (in SINGLE_SELECTION mode).
The first row and column each have an index value of 0.
Lines 7-8: Returns the selected rows or columns (in multiple-selection modes).
Line 9: Selects the whole table.
Line 10: Deselects all selected columns and rows.

Make sure when you call a method that it takes account of the current selection mode.

Lines 11-12: Returns the current row or column number for the table.
Line 13 Allows you to access the element at the position (row, column). Both indexes begin at
0. Accessing the table outside its range leads to an ArrayIndexOutOfBoundsException.

SAP AG JA200 3-82
SAP AG 2003
Table model: TableModel Interface
1 public int getRowCount()
2 public int getColumnCount()
3 public String getColumnName(int columnIndex)
4 public Class getColumnClass(int columnIndex)
5 public boolean isCellEditable(int rowIndex, int columnIndex)
6 public Object getValueAt(int rowIndex, int columnIndex)
7 public void setValueAt(Object aValue, int rowIndex, int columnIndex)
8 public void addTableModelListener(TableModelListener l)
9 public void removeTableModelListener(TableModelListener l)
For sophisticated applications, we recommend that you use a
table model. To do this, implement the
javax.swing.table.TableModel interface.
javax.swing.table
<<Interface>>
TableModel
<<Interface>>
TableModel



n TableModel Interface
The JTable data model is provided as an interface. This means that you can use different classes that
implement this interface.
Most of these predefined methods are service methods called by JTable to get information about the
display of the table.
Lines 1-2: Returns the number of rows or columns respectively.
Line 3: Returns the column header
Line 4: Returns the type of the elements of a column.
Line 5: Specifies whether users can edit the specified cell or not.
Line 6: Allows the table to get the value of the specified cell from the model.
Line 7: Writes a changed value to the model.
Line 8-9: Registers or deregisters a listener that is informed when the model changes (for
example, when a column is inserted, deleted, or changed).

The JTable registers itself with its model, so that it can react to changes in the model by changing the
user interface appropriately.

SAP AG JA200 3-83
SAP AG 2003
The Table Model: The AbstractTableModel Class
Using the AbstractTableModel Class
javax.swing.table
<<Interface>>
TableModel
<<Interface>>
TableModel
Abstract
TableModel
3 public int getRowCount()
4 public int getColumnCount()
5 public Object getValueAt(int row, int column);
Derive a model class from AbstractTableModel and implement all
the methods that do not meet your needs, such as:
You must overwrite the following methods in the model class,
since they are abstract in the AbstractTableModel:
1 public
2 public



n AbstractTableModel class
The AbstractTableModel class implements the TableModel interface and provides and default
implementation for some methods.
Line 1: Implemented but empty; you only need to adapt it yourself if you are using an editable
data model.
Line 2: Returns false by default; you must override it if using an editable data model.
Line 3: Returns the number of rows in the table.
Line 4: Returns the number of columns in the table.
Line 5: Returns the element at the position row, column.

SAP AG JA200 3-84
SAP AG 2003
The Table Model: The AbstractTableModel Class
1 public class TestTable extends JFrame {
2 private Object tableData[][] =
{ {"VW", "New Beetle", new Integer(20425)},
{"Ford", "Transit", new Integer(354590)},
{"Audi", "A2", new Integer(3572)} };
3 private String columnNames[] = {"Make", "Model", "Mileage"};
4 private JTable table;
5 public TestTable() {
6 TableModel myTableModel =
new AbstractTableModel() {
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return tableData.length; }
public Object getValueAt(int row, int col) {
return (Object)tableData[row][col];
}
};
7 table = new JTable(myTableModel);
8 Container cp = getContentPane();
9 cp.add(new JScrollPane(table), "Center");
10 cp.add(createButtonPanel(), "South");
11 }
12 // . . .
13 }
Demo



n Using the AbstractTableModel class
Line 6: Creates a TableModel instance using a local class. The getColumnCount(),
getRowCount(), and getValueAt() methods are overridden in the local class.
Line 7: A JTable instance is created. A reference is made to the TableModel instance.

This simple example allows you only to display elements in a table. You cannot, for example,
change the model.

SAP AG JA200 3-85
SAP AG 2003
JTable
JTable
<<Interface>>
TableModel
Listener
<<Interface>>
TableModel
Listener
The Table Model: The AbstractTableModel Class
Event Trigger
tableChanged()
Event Listener
Table
ModelEvent
When you create an editable TableModel you must trigger
specific events whenever the user makes changes
The AbstractTableModel provides a range of fireXXX
methods for this purpose:
fireTableDataChanged(), fireTableStructureChanged(),
fireTableRowsInserted(), fireTableRowsUpdated(),
fireTableRowsDeleted(), fireTableCellUpdated()
fireTableChanged(TableModelEvent)
AbstractTable
Model



n TableModelEvent
When an event occurs, an object instance of the TableModelEvent class is created and filled with the
data using the event - by means of constants, among other elements.
Internally, the AbstractTabelModel contains a array of TableModelListener references, which is then
processed.
The tableChanged() method is then called for each listener, receiving the TableModelEvent instance
as an argument.

SAP AG JA200 3-86
SAP AG 2003
JTable
JTable
<<Interface>>
TableModel
Listener
<<Interface>>
TableModel
Listener
The Table Model: The AbstractTableModel Class
1 public class TestTable extends JFrame {
// . . .
2 private void addTableRow() {
3 int dim1 = tableData.length;
4 int dim2 = tableData[0].length;
5 Object[][] newTableData = new Object[dim1+1][dim2];
6 System.arraycopy(tableData,0,newTableData,0,dim1);
7 tableData = newTableData;
8 tableData[dim1][0] = "VW";
9 tableData[dim1][1] = "Bully";
10 tableData[dim1][2] = new Integer(20425);
11 AbstractTableModel aTabModel = (AbstractTableModel)table.getModel();
12 aTabModel.fireTableRowsInserted(0,dim1);
13 }
// . . .
14 }
Event trigger
tableChanged()
Event listener
Table
ModelEvent
AbstractTable
Model



Triggering a TableModelEvent
Line 2: In the above example, the addTableRow() method is called when the user chooses the
Add button.
Lines 8-9: A new line is inserted in the data model (not in the table).
Line 12: The table must be informed that the model has changed. The program does this using
the fireTableRowsInserted() method of the AbstractTableModel instance.

SAP AG JA200 3-87
SAP AG 2003
The Table Model: The AbstractTableModel Class
Using the AbstractTableModel Class
javax.swing.table
<<Interface>>
TableModel
<<Interface>>
TableModel
Abstract
TableModel
Default
TableModel
Data in the form of object arrays or vectors
Constructors
getDataVector, getValueAt, void setDataVector, setValueAt
Columns or rows
addColumn, addRow, insertRow, getColumnName, moveRow,
removeRow, getColumnCount, getRowCount
Editing elements



n The DefaultTableModel class
This class is derived from the AbstractTableModel, which offers default implementations for almost
all the methods you need, along with some auxiliary methods (such event handlers).


SAP AG JA200 3-88
SAP AG 2003
The Table Model: The DefaultTableModel Class
1 public class TestTable extends JFrame {
2 private Object tableData[][] =
{ {"VW", "New Beetle", new Integer(20425)},
{"Ford", "Transit", new Integer(354590)},
{"Audi", "A2", new Integer(3572)} };
3 private String columnNames[] = {"Make", "Model", "Mileage"};
4 private JTable table;
5 public TestTable() {
6 TableModel myTableModel =
new DefaultTableModel(tableData, columnNames);
7 table = new JTable(myTableModel);
8 Container cp = getContentPane();
9 cp.add(new JScrollPane(table), "Center");
10 cp.add(createButtonPanel(), "South");
11 }
12 private void addTableRow() {
13 Object[] newRow = {"VW", "New Beetle", new Integer(20425)};
14 DefaultTableModel dTabModel = (DefaultTableModel)table.getModel();
15 dTabModel.addRow( newRow );
16 }
17 // . . .
18 }
Demo



n Using the DefaultTableModel
Line 6: Creates a DefaultTableModel instance. The object array for the data and a string array for
the column headers are passed as arguments.
Line 7: A JTable instance is created. A reference is made to the DefaultTableModel instance.
Line 10: Buttons are created in the example program as well as the table itself, enabling users to
insert, delete, and edit data records.
Line 12: Runs when the user chooses the Add button.
Line 14: You can get a reference to the DefaultTableModel instance using the getModel() method.
Remember, however, that this method returns only an interface reference (of the type TableModel)
and that you must therefore cast to the DefaultTableModel .
Line 15 You can change the data in this model at any time. Changes are passed from the
DefaultModel to the event listener and processed there. The most important event listener may be
JTable itself, which must refresh the display to reflect changes.

SAP AG JA200 3-89
SAP AG 2003
The Column Model: The TableColumnModel
Interface
javax.swing.table
<<Interface>>
TableColumn
Model
<<Interface>>
TableColumn
Model
DefaultTable
ColumnModel
The TableColumnModel interface defines the properties of the
columns in a table
TableColumn
// . . .
1 DefaultTableColumnModel myColModel =
new DefaultTableColumnModel();
2 for( int idx = 0; idx < columnNames.length; idx++ ) {
3 TableColumn tabCol =
new TableColumn( idx, idx==1 ? 50 : 150 );
4 tabCol.setHeaderValue(columnNames[idx]);
5 myColModel.addColumn(tabCol);
6 }
7 table = new JTable(myTableModel, myColModel);
// . . .
Demo



n Column model
A column model is usually created implicitly from the table model and specified column names. If
you want to control column properties apart from the column names, you must create your own
column model.

To do this, you either create your own class, which must implement the TableColumnModel
interface, or you make use of the DefaultTableColumnModel class. This class provides methods that
allow you to insert or delete column objects (of the type TableColumn).

Line 1: Creates an instance of the DefaultTableColumnModel class.
Line 3: Creates an instance of the TableColumn class for each column. The first parameter
specifies the column index, while the second specifies the column width.
Line 4: Sets the column header.
Line 5: The column is added to the model.
Line 7: The column model is passed to the JTable constructor with the table model.

SAP AG JA200 3-90
SAP AG 2003
The TableCellRenderer Interface
Renderers are responsible for displaying the table cells on the
screen.
public TableCellRenderer getDefaultRenderer(Class columnClass)
public void setDefaultRenderer(Class columnClass, TableCellRenderer renderer)
JTable has a default renderer (an instance of the
DefaultTableRenderer class, which implements
TableCellRenderer), which you access with these methods:
javax.swing.table
<<Interface>>
TableCell
Renderer
<<Interface>>
TableCell
Renderer
DefaultTable
CellRenderer
JLabel
javax.swing
Component getTableCellRendererComponent(
JTable table, Object value,boolean isSelected,
boolean hasFocus, int row, int column);
The TableCellRenderer interface predefines the following
methods:



n Renderers
By default, JTable uses an instance of the class DefaultTableCellRenderer to render cells. This class
is a subclass of JLabel. The color, font, and background of table cells can be changed.

Only one instance of the class DefaultTableCellRenderer is created for each table and is used to
display all its cells.

SAP AG JA200 3-91
SAP AG 2003
The TableCellRenderer Interface
1 public class TestTable extends JFrame {
2 public TestTable() {
// . . .
3 myTableModel = new AbstractTableModel() {
// . . .
4 public Class getColumnClass( int col ) {
5 return col==2 ? Integer.class : String.class;
6 }
7 };
// . . .
8 table.setDefaultRenderer( Integer.class, new ColoredIntTabCellRenderer() );
// . . .
9 private class ColoredIntTabCellRenderer implements TableCellRenderer {
10 public Component getTableCellRendererComponent(
11 JTable table, Object value, boolean isSelected,
12 boolean hasFocus, int row, int column ) {
13 int intVal = ((Integer)value).intValue();
14 JLabel label = new JLabel(""+intVal);
15 if ( hasFocus ) {
16 label.setForeground( Color.blue );
17 } else {
18 label.setForeground( Color.red );
19 }
// . . .
20 return label;
21 }
Demo



Renderers
In the above example an internal class, ColoredIntTabCellRenderer, is inserted in the example class
TestTable. It displays the integer values in the last column in either blue or red.
Line 4: The TableModel also overrides the getColumnClass() method.
By default, this method returns Object.class for each column. In the above example, the
method returns String.class for columns 1 and 2 and Integer.class for the last column.
Line 9: The internal class implements the TableCellRenderer interface.
Line 10: The getTableCellRendererComponent method is overridden such that the integer values
in the last column are displayed in red or blue depending whether or not the cell currently has
focus.
Line 8: The renderer is added to the JTable.

Note: There is one disadvantage with the renderer shown in this example: It creates a new JLabel
instance every time getTableCellRendererComponent() is called. This may happen often (when the
mouse cursor moves over the table). If you decide to create your own renderer to solve this problem,
you should use caching or a similar technique.

SAP AG JA200 3-92
SAP AG 2003
Sorting
See the How To... series on Sun's Java Web site:
http://java.sun.com/docs/books/tutorial/uiswing/components/example-
swing/index.html#TableSorterDemo
Sun recommends:
TableModel
Model Sorter View
TableModel
TableModelListener TableModelListener
Sorts the table by the column selected by the user
Uses the TableSorter and TableMap classes (not
included in the JDK)
Demo using the above model



n Sorting
When data is organized in a collection of business objects, sorting and then displaying it in JTables is
relatively complex.
Sun recommends that you insert a sorter between the unsorted model and the view. For sample code
for a sorter, refer to the Web address on the slide.
If you are working with collections, it may be more appropriate to sort the collection itself, rather
than the table. If no duplicate objects occur in the application that is to be displayed in the table, you
should implement a SortedSet - for example, TreeSet. A comparator implementation that controls
sorting can be passed to the TreeSet by the constructor. The TreeSet is then assigned to each event.
However, you can no longer access an object directly using the index.
You can only do this using a List implementation, which has the disadvantage that it always needs to
be re-sorted.

SAP AG JA200 3-93
SAP AG 2003
Headers
JTable column headers are only displayed if the JTable is
added to a JScrollPane
Container cp = getContentPane();
cp.add(new JScrollPane(table), "Center");
cp.add(createButtonPanel(), "South");
JTable
JScrollPane




SAP AG JA200 3-94
SAP AG 2003
The JTree API
<<Interface>>
TreeNode
<<Interface>>
TreeNode
<<Interface>>
TreeModel
<<Interface>>
TreeModel
Default
TreeModel
TreePath
<<Interface>>
TreeCell
Renderer
<<Interface>>
TreeCell
Renderer
<<Interface>>
TreeSelection
Model
<<Interface>>
TreeSelection
Model
javax.swing.tree javax.swing
DefaultMutable
TreeNode
DefaultTree
CellRenderer
The JTree API
is one of the
most complex
APIs in Swing
JTree
Root
The initial element in the tree
Node
An element in the tree
Supernode (parent node)
Superordinate element of a node
Subnode
The elements included under a node
Endnodes
Nodes that have no subnodes
( )
DefaultTree
SelectionModel




SAP AG JA200 3-95
SAP AG 2003
The JTree Class
The JTree class allows users to display, edit, and navigate
through hierarchical data structures (that is, tree structures)
JTree
1 public JTree(TreeNode root)
2 public JTree(TreeModel newModel)
3 public void setRootVisible(boolea rootVisible)
4 public boolean isRootVisible()
5 public TreeModel getModel()
6 public TreePath getSelectionPath()
7 public addTree<xxx>Listener(Tree<xxx>Listener)



Important methods in the JTree class
You can create objects in this class using two different constructors (essentially of equal value):
Line 1: The root node of the tree is passed as a parameter and automatically included in an
appropriate TreeModel by the constructor.
Line 2: A predefined TreeModel for displaying the elements of the tree is passed as a
parameter.

A TreeModel encapsulates all the relevant information about the structure of the tree. When queried,
it returns the root node, provides information about a specific node, or returns that node's subnodes.
JTree always queries the TreeModel for the data it needs to display the tree, or to allow users to
navigate through it.

Lines 3-4: Specifies whether or not the root node of the tree is to be shown or hidden when the
tree is displayed.
Line 5: Returns the model used to supply the data for the tree.
Line 7: Adds an appropriate Listener to the tree for a specified tree event.

SAP AG JA200 3-96
SAP AG 2003
The MutableTreeNode interface (an extension of TreeNode)
provides for inserting and deleting nodes (among others)
1 public DefaultMutableTreeNode(Object userObject)
2 public void add(MutableTreeNode newChild)
3 public void insert(MutableTreeNode newChild,
int childIndex)
4 public void remove(int childIndex)
5 public void removeAllChildren()
6 public void setUserObject(Object userObject)
7 public Object getUserObject()
8
DefaultMutable
TreeNode
<<Interface>>
Mutable
TreeNode
<<Interface>>
Mutable
TreeNode
<<Interface>>
TreeNode
<<Interface>>
TreeNode
The JTree API: Classes and Interfaces



n Important methods in the DefaultMutableTreeNode class
Line 1-7 Defined using the MutableTreeNode interface
Line 2: Inserts a new endnode at the end of the list of subnodes.
Line 3: Inserts a new endnode at the specified position.
Line 4: Removes the specified endnode.
Line 5: Removes all endnodes.
Lines 6-7: You can store application-specific information in a UserObject, and then pass this to
the constructor. You can then access this information using the appropriate set/get
methods. The UserObject also supplies the node label: Each call of the toString() method is
passed to the UserObject.
Lines 8-11: Defined by the TreeNode interface.
Line 8: Returns the number of subnodes (numbered from 0).
Line 9: Returns the subnode at the specified position.
Line 10: Returns the supernode.
Line 11: Allows you to query whether a node is an endnode, or a subnode that has other subnodes.

To provide node labels when displaying the tree, the JTree uses the toString() method of the node
class.

SAP AG JA200 3-97
SAP AG 2003
The JTree API: Classes and Interfaces
Implements the class that provides the model
(DefaultTreeModel by default)
Implemented by classes
that draw a single tree
element
<<Interface>>
TreeModel
<<Interface>>
TreeModel
Provides a list of objects (such as TreeNodes) in a
tree path
<<Interface>>
TreeCell
Renderer
<<Interface>>
TreeCell
Renderer
DefaultTree
CellRenderer
Default
TreeModel
TreePath
Specifies the behavior
when the user selects or
chooses elements in the
tree
<<Interface>>
TreeSelection
Model
<<Interface>>
TreeSelection
Model
DefaultTree
SelectionModel




SAP AG JA200 3-98
SAP AG 2003
Listeners
<<Interface>>
TreeSelection
Listener
<<Interface>>
TreeSelection
Listener
Is notified whenever an element is selected in a tree
<<Interface>>
TreeExpansion
Listener
<<Interface>>
TreeExpansion
Listener
Is notified whenever an element is expanded or
collapsed
<<Interface>>
TreeExpand
Listener
<<Interface>>
TreeExpand
Listener
Gives information on whether expanding and
collapsing is allowed
<<Interface>>
TreeModel
Listener
<<Interface>>
TreeModel
Listener
Is notified when the data structure of the JTree
changes
The following listeners (and associated events) are available in
the javax.swing.event package:




SAP AG JA200 3-99
SAP AG 2003
Creating a Tree
1 public class TestTree extends JFrame {
2 String[] masterData = { "Vehicle", "Persons", "Locations" };
3 String[] booking = { "b1", "b2" };
4 DefaultMutableTreeNode tnRoot, tnMasterData, tnBooking, tnLeaf;
5 DefaultTreeModel treeModel
6 JTree tree;
7
8 public TestTree() {
9 tnMasterData = new DefaultMutableTreeNode( "MasterData" );
10 for (int idx = 0; idx < masterData.length; idx++ ) {
11 tnLeaf = new DefaultMutableTreeNode( masterData[idx] );
12 tnMasterData.add( tnLeaf );
13 }
14 tnBooking = new DefaultMutableTreeNode( "Booking" );
15 // . . .
16
17 tnRoot = new DefaultMutableTreeNode( "CarControl" );
18 tnRoot.add( tnMasterData );
19 tnRoot.add( tnBooking );
20 treeModel = new DefaultTreeModel(tnRoot);
21 tree = new JTree( treeModel );
22 // . . .
23 tree.setRootVisible( true );
24 this.getContentPane().add(new JScrollPane(tree), "Center");
25 }
26 }
JTree
Default
TreeModel
DefaultMutable
TreeNode



n Lines 4-6: Defines the TreeNodes, the model, and the tree.
Lines 9-12: Creates the MasterData node. All the objects in the masterData array are inserted in
the MasterData node as subnodes, using a loop.
Line 17: The root node is defined. The MasterData node is added to it, among others.
Line 20: The TreeModel is instantiated and the root node passed to the constructor.
Line 21: The tree is instantiated and the model passed to the constructor.

SAP AG JA200 3-100
SAP AG 2003
Selecting and Querying Nodes
<<Interface>>
TreeSelection
Model
<<Interface>>
TreeSelection
Model
DefaultTree
SelectionModel
JTree
2 public void setSelectionModel(TreeSelectionModel selectionModel)
3 public TreeSelectionModel getSelectionModel()
4 public TreePath getSelectionPath()
5 public TreePath[] getSelectionPaths()
6 public TreePath getLeadSelectionPath()
7 public boolean isSelectionEmpty()
8 public boolean isPathSelected(TreePath path)
1 public void setSelectionMode(int mode)
TreePath
9 public Object getLastPathComponent()
10 public Object[] getPath()
11 public void valueChanged(TreeSelectionEvent event)
<<Interface>>
TreeSelection
Listener
<<Interface>>
TreeSelection
Listener
TreeSelectionEvent
12 public TreePath getOldLeadSelectionPath()
13 public TreePath getNewLeadSelectionPath()




SAP AG JA200 3-101
SAP AG 2003
Selecting and Querying Nodes
JTree
DefaultTree
SelectionModel
<<Interface>>
TreeSelection
Listener
<<Interface>>
TreeSelection
Listener
1 public class TestTree extends Jframe
implements TreeSelectionListener {
2 // . . .
8 public TestTree() {
9 // . . .
21 tree = new JTree( treeModel );
22 TreeSelectionModel tsm = new DefaultTreeSelectionModel();
23 tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
24 tree.setSelectionModel(tsm);
25 tree.addTreeSelectionListener(this);
26 // . . .
27 }
28 public void valueChanged( TreeSelectionEvent event ) {
29 TreePath tp = event.getNewLeadSelectionPath();
30 if (tp != null) {
31 Object[] treeNodes = tp.getPath();
32 System.out.println(" Selected treePath: " + tp.toString());
33 System.out.println(" Selexcted node: " +
tp.getLastPathComponent().toString());
34 } else {
35 System.out.println(" nothing selected ");
36 }
37 }
38 }
Tree
SelectionEvent
TreePath



Line 21: The tree is instantiated and the model passed to the constructor.
Line 22: The TreeSelectionModel is instantiated.
Line 24: The TreeSelectionModel is added to the tree.
Line 25: The class registers itself with the tree as a listener. To do this, it implements the
TreeSelectionListener (line 1) and the valueChanged method (line 20).

SAP AG JA200 3-102
SAP AG 2003
Changing the Tree Structure
<<Interface>>
TreeModel
<<Interface>>
TreeModel
1 public void insertNodeInto( MutableTreeNode newChild,
MutableTreeNode parent, int index )
2 public void removeNodeFromParent(MutableTreeNode node)
3 public void nodeChanged(TreeNode node)
4 public TreeNode[] getPathToRoot(TreeNode aNode)
Changes to the tree (that is, inserting, changing, or deleting
nodes) must be made using the model, since the JTree is
registered there as a TreeModelListener by default, and as such
is always informed of changes
Default
TreeModel




SAP AG JA200 3-103
SAP AG 2003
JTree
Default
TreeModel
1 public class TestTree . . . {
8 public TestTree() {
17 tnRoot = new DefaultMutableTreeNode( "CarControl" );
18 tnRoot.add( tnMasterData );
19 tnRoot.add( tnBooking );
20 treeModel = new DefaultTreeModel(tnRoot);
21 tree = new JTree( treeModel );
22 }
39 public void addTreeChild() {
40 TreePath tp = tree.getLeadSelectionPath();
41 if (tp != null) {
41 DefaultMutableTreeNode node;
43 node = (DefaultMutableTreeNode)tp.getLastPathComponent();
44 DefaultMutableTreeNode child;
45 child = new DefaultMutableTreeNode("child");
46 treeModel.insertNodeInto(child, node, node.getChildCount());
47 TreeNode[] path = treeModel.getPathToRoot(node);
48 tree.expandPath(new TreePath(path));
49 }
50 }
Changing the Tree Structure
Demo



n Line 21: The tree is instantiated and the model passed to the constructor.
Line 46: Operations to data in the tree are performed by means of the TreeModel.
Line 48: To make the inserted data visible, you call the expandPath(...) method.

SAP AG JA200 3-104
SAP AG 2003
Menus
Components 2
Button
Combo box
List
Components 1
Labels
Text fields
Containers Swing properties
Swing Overview 8
Components 3
Dialogs
Components 4
Tables
Trees
1
2
3
4
5 6
7
Events
8



n Swing properties
This section deals with the foundations and concepts of Swing. The following terms are explained:
Lightweight/heavyweight components
Top/2nd level components
Look & Feel
Model View Controller pattern (MVC)
n Containers
This section describes the general container classes that you can use to create a GUI.
n Components part 1
This chapter introduces the text-based dialog components.
n Menus
In Swing all windows, with the exception of JWindow, can be equipped with a menu bar.
n Components part 2
This chapter deals with the buttons provided by Swing.
n Components part 3
You can use the classes JFileChooser, JColorChooser, and JOptionPane to create user dialogs
simply.
n Components part 4
Trees and tables are complex user interfaces with the most frequently used dialog elements.

SAP AG JA200 3-105
SAP AG 2003
Assigning Event Types to Components
JButton
JCheckBox
JColorChooser
JComboBox
JDialog
JEditorPane
JFileChooser
JFrame
JInternalFrame
JList
A
c
t
i
o
n
C
a
r
e
t
C
h
a
n
g
e
D
o
c
u
m
.
I
t
e
m
L
i
s
t
S
e
l
.
W
i
n
d
o
w




SAP AG JA200 3-106
SAP AG 2003
JMenu
JMenuItem
JOptionPane
JPasswordField
JPopupMenu
JProgressBar
JRadioButton
JSlider
JTabbedPane
JTable
A
c
t
i
o
n
C
a
r
e
t
C
h
a
n
g
e
D
o
c
u
m
.
I
t
e
m
L
i
s
t
S
e
l
.
W
i
n
d
o
w
Assigning Event Types to Components (2)




SAP AG JA200 3-107
SAP AG 2003
JTextArea
JTextField
JTextPane
JToggleButton
JTree
JViewport
A
c
t
i
o
n
C
a
r
e
t
C
h
a
n
g
e
D
o
c
u
m
.
I
t
e
m
T
r
e
e
S
e
l
.
W
i
n
d
o
w
Assigning Event Types to Components (3)




SAP AG JA200 3-108
SAP AG 2003
Summary
You are now able to:
l Describe the general architecture of Swing
l Work with the most important components of Swing
l Use the Model View Controller architecture
l Use the events of the Swing components for
programming




SAP AG JA200 3-109
JFC, SWING Exercises 1


Unit: JFC: Swing
Topic: Component Development Optional Exercise

At the conclusion of this exercise, you will be able to:
Provide your own graphical component (control).

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 1. Take a look at the graphic(s).
JVIEWER

Note:
Being able to develop your own components is always important if you require particular
functions for your application that are not covered by the standard classes in JDK. In this
exercise, you will develop a simple control that is available in this form only as of JDK 1.4: the
JSpinner class. This class represents an input field that can increase or decrease values
through incorporated buttons.

3-1 Create the class Jspinner.
Create the package com.sap.epf.ja200.exc.lab03 and call it up. Define the class
JSpinner. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.
You should derive this class from the class javax.swing.JComponent.
Attributes
Modifier Type Name
private int value
private int min
private int max
private int adjustSize
private JTextField textField
private JButton btnUp
private JButton btnDown
These variables are filled with values by the constructor.

First provide the following (still empty) constructor:
Modifier Return type Name/parameter list
public JSpinner(int value, int min,
int max, int adjustSize)

SAP AG JA200 3-110
In the constructor, assign the passed parameter values to the attributes of the same
name.

3-2 First provide the following (still empty) methods:
Modifier Return type Name/parameter list
public int getValue()
This method returns the value of the attribute value.

Modifier Return type Name/parameter list
private void displayValue( int newValue )
This method is always called whenever the value changes.

3-3 Implement the constructor.

The constructor is called as follows:
JSpinner(int value, int min, int max, int adjustSize)
int value The initial value is passed here:
int min This attribute defines the minimum value up to which the
value may be decremented.
int max This attribute defines the minimum value up to which the
value may be incremented.
int adj. This attribute defines the increment steps for incrementing/decrementing.

In the constructor, assign the passed parameter values to the attributes of the same
name.

Use the GridbagLayoutManager for your component.
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.NONE;

this.setLayout( gbl );
. . .
this.add( pnl, gbc );
Explanation: The parameter gridx specifies the column of the logical grid where the
left border of the dialog element is to be. The first column has the value 0. In the same
way, gridy specifies the logical line of the upper border of the dialog element. Both
values define the position within the logical grid. Here, (0, 0) is the left upper corner.
The parameters gridwidth and gridheight specify the horizontal and
vertical dimensions of the dialog element.
The paramter fill defines how the measurements of the dialog element change when
the size of the window changes.


SAP AG JA200 3-111
Define a JPanel into which the JTextField and the corresponding JButtons
can be inserted.

Assign a valid JTextField object to the reference variable textField. textField
should not be editable.

Define a local variable sizeText of the type Dimension and assign the PreferredSize
from textField to it.

Define a further JPanel pnlBut that is to include the buttons.

Assign the valid Jbutton object to the variables butUp and butDown.
Assign the strings increase and decrease to the ActionCommmands using the
corresponding set method.
Set the size of the buttons to width 25 and height sizeText / 2.

Assign a GridLayoutManager (2 lines, 1 column) to the JPanel pnlBut and place
butUp and btnDown into it.
Set the size for pnlBut to width 25 and height sizeText.

Add textField in the center and pnlBut in the east of JPanel pnl.
Call the method displayValue and pass on the value.


SAP AG JA200 3-112
3-4 Implement the main method.

Create a Jframe instance. Add a JPanel to the Jframe (BorderLayout). Add
an instance of the class JSpinner to the JPanel. Make the JFrame visible.

Compile and test the class. A JFrame with the new control should appear. Continue
with the next exercise in order to display the values and be able to manipulate them.
3-5 Implement the displayValue(int newValue) method.

This method is passed the newValue. First check whether the value lies within the
min./max. range (variables min, max are already given to the JSpinner constructor).
If not, the newValue should get the corresponding limit value.
Assign the newValue to the attribute value. Assign the value to the JtextField.
3-6 Implement the ButtonListener LocalActionListener as internal class.

Implement the interface ActionListener. In the actionPerformed method
that is defined there, access the ActionCommands for the buttons. If there has been an
increment, call the method displayValue with the value + adjustSize. Proceed in the
same way if the decrement button was pressed.

Assign an instance of the class LocalActionListener to the buttons btnUp and btnDown
in the constructor for JSpinner.
3-7 Implement the KeyListener LocalKeyListener as internal class.

Implement the interface KeyListener as empty, that is, define only the respective
method header and leave the method bodies empty. This interface defines the methods
keyReleased, keyTyped, and keyPressed. Implementieren Sie die ersten
beiden Methoden leer. Implement the method keyPressed as follows:
Access the KeyCode using the KeyEvent object. Compare this keyCode with the
constants of the class KeyEvent: VK_UP, and VK_DOWN. Accordingly, call the
displayValue() method with the incremented/decremented value.

Compile and test the new component.



SAP AG JA200 3-113
JFC, SWING Exercises 2


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 1

At the conclusion of this exercise, you will be able to:
Program a logon screen with user ID, password entry, and language
selection.

Note:
The course JA200 GuiKit is based on a vehicle model that is discussed in detail in the
course JA100 StartUpKit. The classes of this course are available as .jar files and can be
used throughout the remainder of the exercises, provided you have made the relevant
project settings in the IDE.

Since you only use defined interfaces of JA100 classes in the exercises, you require no
knowledge of the internal structure and functions of these classes.

In the following exercises, you will program a GUI, step by step, using Swing classes for the
vehicle model. Please note that some exercises are optional, depending on the time available.

3-8 Create the main class CarControllApp.

Create the package com.sap.epf.ja200.exc.lab03 and call it up.
Define the CarControllApp. class. Make the class public and include it in the
package com.sap.epf.ja200.exc.lab03.

Import the following classes/packages.
import com.sap.epf.ja100.app.*;
import com.sap.epf.ja100.cmd.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.util.*;
import java.util.*;

Derive your class or implement the following interfaces:
implements ICarControl
The interface com.sap.epf.ja100.app.ICarControl does not define any
methods. It is used merely as a signal function.


Define the following attributes:
Modifier Typ Name
private PersistManager persistMan
private CommandManager cmdMan

SAP AG JA200 3-114
private GuiManager guiMan
Line 1: The class com.sap.epf.ja100.persist.PersistManager is provided
for loading the persistent data and creating the objects for the vehicle model.
Line 2: The class com.sap.epf.ja100.cmd.CommandManager acts as controller
and is reponsible for the communcation between the user interface and the model data.
Line 3: The GuiManager creates all the necessary GUI instances.

First comment out these lines. These attributes will be required only later!

Define the following constructor (empty at first):
Modifier Name/parameter list
public CarControlApp()

Define the following methods (empty at first):
Modifier Return type Name/parameter list
private void setProperties()
public void callBackFromLogon()
public
static
void main( String[] args )
Line 1: In this method, the program attributes are imported from the file JA200.ini into
an object of the class com.sap.epf.ja100.util.StaticData. This class provides
static methods with which you can read the program attributes, as required.
Line 2: This method is called as soon as the user has finished the logon dialog through
pressing the Ok button.
Line 3: The main method is the starting point for the application. The constructor for
the class CarControlApp is called here.

3-9 Implement the method/s):

private void setProperties() {
try {
StaticData.setProperties (
com.sap.epf.ja200.app.CarControlApp.class,
"JA200.ini" );
} catch (Exception exc) {
System.out.println("Error loading Properties ");
System.out.println(exc.getMessage());
}
}
In this method, the program attributes are imported from the ini file JA200.ini and
provided in an object of the class com.sap.epf.ja100.util.StaticData.
The ini file must be in the same directory as the class
com.sap.epf.ja200.app.CarControlApp.

3-10 Implement the constructor.

public CarControlApp() {
}

SAP AG JA200 3-115
First call the setProperties() method in the constructor.
Then call the method init() of the class com.sap.epf.ja100.util.Csystem.

3-11 Implement the main method.
public static void main( String args[] ) {
}
Create a local object of the class CarControlApp.

3-12 Create the logon screen DialogLogon
Help:
Start JViewer. In the directory tree, choose the node Exercises
+ lab03 12. Take a look at the graphic(s).
JVIEWER
The logon screen is to appear at the start of the application. The logon screen is to consist of the
following components:
JTextField For entering the user ID
JPasswordField For entering the password
JCombobox For choosing the language (German, English, and French)
JButton For terminating the application (Cancel)
JButton For starting the application (Ok)

The logon screen is to be called by the constructor of the class CarControllApp.
When the user starts the application (Ok), the logon screen calls the method callBackFromLogon of the
class CarControllApp. Now further processing takes place. If not, the application is terminated.
Now try to carry out a logon dialog on your own, or continue with the step-by-step description.
Note: To display the icon, refer also to exercise 3-14.

3-13 Logon screen DialogLogon

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the DialogLogon class. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.

Import the following classes/packages.
import com.sap.epf.ja100.app.ICarControl;
import com.sap.epf.ja100.util.IconFactory;
import java.util.*;

Derive your class or implement the following interfaces:
extends JDialog

Define the following attributes:
Modifier Type Name
private JTextField txtUser
private JPasswordField txtPassword
private JComboBox cbLang
private IConFactory.Multi
Icon
multiIcon

SAP AG JA200 3-116
private ICarControl icc
Line 1: Input field for user Ids.
Line 2: Input field for password.
Line 3: Selection box for languages.
Line 4: You can use the inner class com.sap.epf.ja100.util.IconFactory.MultiIcon
to load and display icons.
Line 5: The reference to the main program CarControlApp is kept in this variable in
order to be able to call the method callBackFromLogon using it.

Define the following constructor (empty at first):
Modifier Name/parameter list
public DialogLogon(ICarControl icc)

Define the following methods (empty at first):
Modifier Rckgabetyp Name/Parameterliste
private JPanel initWest()
private JPanel initCenter()
private JPanel initSouth()
public void showIt()
Line 1-3: The individual areas of the dialog screen are initialized in these methods.
Line 4: Using this method, you start the dialog on your desktop.

3-14 Implement the method(s):

private JPanel initWest() {
}
An icon is to appear in this area.
First define a local variable of the class JPanel.
Assign an icon to the icon variable multiIcon. For this purpose, use the (prepared) class
com.sap.epf.ja200.sol.lab03.StaticGuiData:
multiIcon = StaticGuiData.iFac.getIcon( "ScrJA200" );

First define a local variable of the class JLabel. Call the constructor as follows:
label = new JLabel( multiIcon.getInitialScaled(160,160));

Enter the label into the panel and return the panel.

3-15 Implement the method(s):

private JPanel initSouth() {
}
In this area, you want 2 buttons to appear (Ok and Cancel).
First define a local variable of the class JPanel. Assign a FlowLayout, alignment
right, to the panel.
Define 2 Jbuttons. To label the buttons, use the prepared class
com.sap.epf.ja200.sol.lab03.StaticGuiData:
bCnc = new JButton(StaticGuiData.res.getRsrc("cancel"));

SAP AG JA200 3-117
bOk = new JButton(StaticGuiData.res.getRsrc("ok"));
Add the buttons to the panel and return the panel.

3-16 Implement the method(s):

private JPanel initCenter() {
}
In this area, you want to have the input fields for user ID, password, and a selection box
for the language setting.
First define a local variable of the class JPanel. Assign a GridLayout (6 lines, 2
columns) to the panel. Define 3 local variables of the class JLabel. Use the
(prepared) class for labelling the label.
com.sap.epf.ja200.sol.lab03.StaticGuiData:
new JLabel(StaticGuiData.res.getRsrc("user")
new JLabel(StaticGuiData.res.getRsrc("password")
new JLabel(StaticGuiData.res.getRsrc("language")
Fgen Sie die Labels entsprechend dem Panel hinzu.

First define a local variable of the class JTextField. Add the text field to the panel.
Define a local variable of the class JPasswordField. Add the password field to the
panel.
The user ID and password are not processed further at this point.
Sie knnen selbst eine Methode zur Verifizierung hinzufgen.

Define a local variable of the class JComboBox. Add the strings German, English, and
French into the selection box.
Add the ComboBox to the Panel.

Add the buttons to the panel and return the panel.

3-17 Implement the method(s):

private void showIt() {
}
In this method, you make the settings (window size and so on) for the dialog and the
dialog becomes visible.
Assign the size 380/200 (width/height) to the dialog. The dialog should be a modal
dialog and it must not be possible to enlarge it or minimize it. Finally, make the dialog
visible.

3-18 Implement the constructor.

public DialogLogon( ICarControl icc ) {}
First, call the superclass constructor.
super(new JDialog(),StaticGuiData.res.getRsrc("logon"));
Assign the parameter icc to the attribute of the same name.
Define a BorderLayout for the dialog.

SAP AG JA200 3-118
Add the suitable panels to the positions EAST, WEST, and SOUTH by calling the
corresponding methods.

3-19 Define an internal class to react to the button events.
private class LocalButtonAction
implements ActionListener {
}
Define a variable of the type DialogLogon within this inner class.
Define a constructor that receives a parameter of the type DialogLogon. Assign the
passed value within the constructor to the variable of the type DialogLogon.
Define the method actionPerformed(...) predefined by the interface as follows:
When the user presses the Cancel button, terminate the application.
When the user presses the Ok button, create a local variable loc of the type Locale.
Read the entry chosen by the user in the language selection box and store this value in
the local string variable lang. Depending on the value in lang, assign a valid local
object to the local variable, for example English:

if (lang.equals(Locale.ENGLISH.getDisplayLanguage()) ){
loc = new Locale( Locale.ENGLISH.getLanguage(),
Locale.ENGLISH.getCountry() );
Set the system local object to the new value and store these values for the application.
Locale.setDefault(loc);
StaticGuiData.res = JA200Lang.getRsrcBundle();
Hence, you ensure that the correct ResourceBundle object for your application will
be loaded. The reference to this will be stored in the static variable
StaticGuiData.res.

Using the variable icc, call the method callBackFromLogon of the start program
CarControlApp.
3-20 Add the inner class LocalButtonAction to the buttons as Listener.
3-21 Call the class DialogLogon from the class CarControlApp.
In the constructor of CarControlApp, define a local variable of the type
DialogLogon and assign a valid object to it. Afterwards, call the showIt() method.
In the method callBackFromLogon, enter an output statement:
System.out.println("CallBack");
3-22 Call the class DialogLogon from the class CarControlApp.
Compile and test the classes.


SAP AG JA200 3-119
JFC, SWING Exercises 3


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 2

At the conclusion of these exercises, you will be able to:
Program a central class for managing GUI components
(GuiManager).

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 23. Take a look at the graphic(s).
JVIEWER

Note:
The GuiManager class will be started as soon as logon from the class CarControlApp has
been successful. Your main task will be to initialize all GUI components and to provide their
references (stored in a container) for all program parts.

You will adapt this class several times during the exercises.

3-23 Create the GuiManager class.

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the class GuiManeger. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.

Import the following classes/packages.
import com.sap.epf.ja100.app.*;
import java.util.*;
Derive your class or implement the following interfaces:
implements IManager
The interface com.sap.epf.ja100.app.IManager defines the method
registerManager. In this method, a manager class is to register with the class
com.sap.epf.ja100.app.StaticData. Using this method public static
IManager getManager(String key), other program parts, in turn, can access a
manager instance.


Define the following attributes:
Modifier Type Name
private Hashtable guiComponents
Line 1: The hashtable is provided to store all components under one unique name.
Using the corresponding get method, you can have the components read by the

SAP AG JA200 3-120
GuiManager.

Define the following constructor (empty at first):
Modifier Name/parameter list
public GuiManager()

Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void registerManager()
public Object getGuiComponent(String key)
throws NullPointerException
Line 1: In this method, the GuiManager is registered with the class
com.sap.epf.ja100.util.StaticData.
Line 2: With this method, other objects can access registered components from the
hashtable using a prespecified String/Key.

3-24 Implement the method(s):

public void registerManager()
Register the current class under the name gui at
com.sap.epf.ja100.app.StaticData using its method registerManager(...).

public Object getGuiComponent( String key )
throws NullPointerException
In the hashtable guiComponents, search for an entry for the specified key and return the
reference to the found object or trigger a NullPointerException.


SAP AG JA200 3-121
3-25 Implement the constructor.

public GuiManager()
Afterwards, call the registerManager() method. Then, instantiate the reference variable guiComponents.

Compile the class.
3-26 Change the class CarControlApp.

Add the attribute private GuiManager guiMan to the attributes.

Change the method callBackFromLogon:
public void callBackFromLogon() {
persistMgr = PersistManager.getInstance( null );
persistMgr.loadBusObjects();
cmdMgr = CommandManager.getInstance();

}
(Explanation in the solution section.)
After the above statements, initialize the reference variable guiManager. Compile and
test the classes. After you have started the main program, the dialog should appear.
Since no further dialog components were developed, the program will terminate itself
again after execution of the persistence, command, and GuiManager classes. However,
no error should occur.



SAP AG JA200 3-122
JFC, SWING Exercises 4


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 3

At the conclusion of this exercise, you will be able to:
Program the main screen for the car-rental company application.

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 24. Take a look at the graphic(s).
JVIEWER

In the following steps, you will implement the MainScreen class, which is the main screen of
the application. During the course of the exercises using GUI components that are registered in
the Gu8iManager class, this class will be added to further.

3-27 Create the MainScreen class.

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the MainScreen class. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.

Import the following classes/packages.
import com.sap.epf.ja100.util.IconFactory;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

Derive your class or implement the following interfaces:
extends JFrame
implements WindowListener

Define the following attributes:
Modifier Type Name
private GuiManager guiManager
private JComponent cmpNorth,
cmpSouth,
cmpCenter

Define the following constructor (empty at first):

SAP AG JA200 3-123
Modifier Name/parameter list
public MainScreen( GuiManager guiManager )


Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void windowActivated(WindowEvent
e)
public void windowClosed(WindowEvent e)
public void windowClosing(WindowEvent e)
public void windowDeactivated(WindowEven
t e)
public void windowDeiconified(WindowEven
t e)
public void windowIconified(WindowEvent
e)
public void windowOpened(WindowEvent e)
private JPanel createPnlNorth()
private JPanel createPnlCenter()
private JPanel createPnlSouth()
Line 1-7: These methods are defined by the WindowListener interface.

3-28 Implement the method(s):

public void windowClosing(WindowEvent e)
When the window is closed, the application should be terminated.

private JPanel createPnlNorth()
In the north area of the main screen, a title icon should appear on the left-hand side and
the SAP logo should appear on the right-hand side. For this purpose, use a JPanel to
which2 JLabel is assigned and to which you, in turn, assign the appropriate icons
IconFactory.MultiIcon multiIcon =
StaticGuiData.iFac.getIcon("Company"); // bzw, "JA200"
companyLabel.setIcon( multiIcon.getInitial() );

private JPanel createPnlSouth()
In the south area, you want to insert a progress bar. For this purpose, define a local
variable of the JPanel type. Add the progress bar
com.sap.epf.ja200.exc.lab03.StaticGuiData.pBar to this panel, aligned to
the right.
Set its attributes BorderPainted (false) and StringPainted (true) using the corresponding
set methods.


SAP AG JA200 3-124
3-29 Implement the constructor.

public MainScreen( GuiManager guiManager )
First call the constructor of the superclass and enter here the title of the main window.
Initialize the reference variable guiManager with the value of the same-name
parameter. Assign a BorderLayout to the main screen. Assign the return values of
the methods createPnlNorth/South to the attributes cmpNorth and cmpSouth. Place the
panels into the corresponding regions of the main screen. Determine the start position
of the main screen (new Point(200,200)), whose size is (new
Point(600,300)), and add to the class a reference to itself as WindowListener.
1. Register the MainScreen in the GuiManager class.
Open the GuiManager class. In the constructor, insert an instance of the MainScreen
class in the guiComponents hashtable. As key, use the string MainScreen here.

3-31 Start the main screen.
Open the CarControlApp class. At the end of the callBackFromLogon method, have
the GuiManager get the MainScreen component registered there and make the screen
visible. Compile and test the application.



SAP AG JA200 3-125
JFC, SWING Exercise 5


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 4

At the conclusion of this exercise, you will be able to:
Program a menu bar for the main screen
Program menu events
Change the Look & Feel of the GUI

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 + 32. Take a look at the graphic(s).
JVIEWER

In the following steps you will add a menu bar to the main screen.

Create the class MainScreenMenu
Stay in the package com.sap.epf.ja200.exc.lab03.
Define the class MainScreenMenu. Make the class public and include it in the
package com.sap.epf.ja200.exc.lab03.

The class is to be responsible for creating an entire menu bar that will be provided using
a get method. The menu is to be structured as follows:

SAP AG JA200 3-126
Menu items: File, Tools, Help
Menu item File:
Menu subitem Exit
Menu item Tools:
Menu subitem Look & Feel
Menu subitem Motif
Menu subitem Windows
Menu subitem Metal
Menu subitem Display Log File
Menu subitem Settings
Menu item Help:
Menu subitem Documentation
Menu subitem About JA200

Implement the class, initially without an EventListener.
The constructor of the class is to be passed a reference to an object of the GuiManager
class and save it in an identically-named attribute.
Provide a get method with which the menu bar can be accessed.

When labeling the menus, be aware of the current memory settings
With the call StaticGuiData.res.getRsrc("about")you access the current
ResourceBundle. When calling this method, use the keys defined in the
JA200RSrc_xx classes.

3-33 Add the class to the GuiManager.

guiComponents.put(
"MainScreen.Menu", new MainScreenMenu(this) );

3-34 Insert the menu in MainScreen

mainScreenMenu =
(MainScreenMenu)guiManager.getGuiComponent(
"MainScreen.Menu");
this.setJMenuBar( mainScreenMenu.getMenuBar() );
There is a step by step explanation in the solutions.
Compile and test the application; try out different languages.

3-35 In the MainScreen class, define a local class that can be added to the menu items
as a listener.

Help:
Start JViewer. In the directory tree, choose the node Exercises
+ lab03 + 35. Take a look at the graphic(s).
JVIEWER

If the user chooses the menu item Help > About JA200 (caution: Language-specific), a
dialog window is to appear. Use:
StaticGuiData.showAboutInformation();

SAP AG JA200 3-127
3-36 Change the Look & Feel of the interface for the menu item Tools -> Look & Feel.
In the MainScreenMenu class, add the relevant JRadioButtonMenuItem, the
ActionCommands LF_Motif, LF_Windows, and LF_Metal, and the
corresponding local ActionListeners. Extend the case distinction in the
actionPerformed(...) method of the ActionListener: If the ActionCommand starts with
LF_, the GuiManager.setLF( String laf ) method is to be called.
This method becomes responsible for changing the Look & Feel. You will implement it
as your next step:
In the GuiManager class, define the following methods:
Modifier Return type Name/parameter list
public void setLF( String laf )
private void setPlaf( String laf )
private void setLF()
Line 1: This method is passed a string as a parameter, which contains the Look & Feel
to be set. This method calls the two private methods.
Line 2: This method is called by method 1. Using the string passed by method 1, it is
decided here which Look & Feel to set.
Line 3: This method then sets the Look & Feel.

3-37 Implement the method(s):

public void setLF( String laf ) {
}
This method makes up the public interface. It internally calls the methods setPlaf(
String laf ) one after the other (the parameter laf is passed on) and then the setLF()
method.

private void setPlaf( String laf ) {
}
When selecting the relevant menu item, an ActionCommand is triggered and the name
of the command is eventually passed to here as a string by the ActionListener. Using
the ActionCommand string, you must decide here which Look & Feel is to be set.
First save the value of the parameter in the string attribute lookAndFeel and then set
the attribute plaf correspondingly:
lookAndFeel = laf;
if ( lookAndFeel.equals("LF_Metal") ) {
plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
}

private void setLF() {
}
This method sets the Look & Feel. Use the javax.swing.UIManager class. In a
loop, call the method
javax.swing.SwingUtilities.updateComponentTreeUI( Component c );
for all elements of the hashed table guiComponents.


SAP AG JA200 3-128
JFC: Swing Exercise 6


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 5

At the conclusion of this exercise, you will be able to:
Use the component JSplitPane

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 + 38. Take a look at the graphic(s).
JVIEWER

You have already created the main screen, its menu bar, title bar, and status bar. In this
exercise, you will create another class that divides the central area of the main screen into a left
section (for a JTree) and a right section (for JTables).

3-38 Create the class MainScreenWorkbench

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the class MainScreenWorkbench. Make the class public and include it in
the package com.sap.epf.ja200.exc.lab03.

Derive the class from the javax.swing.JSplitPane class.
Pass the constructor a reference to the GuiManager and save it in an attribute. Before
that, call the superclass constructor explicitly.

Implement the following properties:
DividerLocation: 150
Orientation: horizontal
OneTouchExpandable: true
Opaque false

Define a JPanel object for each section. Embed one of them in a JScrollPane.
Insert the JScrollPane into the left section (LaunchPadArea)and the other JPanel
into the right section (ContentPadArea) of MainScreenWorkbench.





SAP AG JA200 3-129
3-39 Register the new component with the GuiManager
Use the key MainScreen.Workbench.

Add the new component to the MainScreen class
Change the constructor of the MainScreen class.
Get the reference to the MainScrenWorkbench object using the GuiManager. Assign
this reference to the attribute pnlCenter. Insert pnlCenter in the center area of the
main screen.

Compile and test the application.


3-40 Extend the MainScreenWorkbench class

Add a JTabbedPane to the ContentArea (right section). Define a method
refreshContent, with which you can add new components to the ContentArea from
outside.

Define the following attributes:
Modifier Type Name
private JTabbedPane tabbedPane
private Vector guiComponents

Define the following methods:
Modifier Return type Name/parameter list
public void trefreshContent( String
newContent )
Line 1: Using this method you can request the workbench from the outside to add new
components to the ContentArea.

Change the constructor
Instantiate the attributes tabbedPane and guiComponents. Add the JTabbedPane
to the right section (ContentArea) of the MainScreenWorkbench class, as defined in
3-38.

Implement the method(s):
public void refreshContent( String newContent )
This method can be used by other objects to add a new component to the JTabbedPane of
the ContentArea. Get a reference to a valid component from the GuiManager. Use the key
Workbench.ContentArea.+newContent.
Check whether such a component already exists in the container guiComponents. If not, add
the component to the guiComponents container and the JTabbedPane.
Add the JTabbedPane to the ContentArea.


SAP AG JA200 3-130
JFC: Swing Exercises 7-1


Unit: JFC: Swing
Topic: Swing GUI for the Car Rental Company,
Part 6-1

At the conclusion of this exercise, you will be able to:
Program a TableModel for a JTable


Help:
Start JViewer. In the directory tree, choose the node Exercises
+ lab03 41. Take a look at the graphic(s).
JVIEWER

Some considerations before you start
In the exercises that follow, you will develop a new component step by step. This component
will display the car rental model in a JTable. Before you develop the JTable class, you will
implement a factory class, which provides TableModel and Table Column classes. This allows
you both to encapsulate the vehicle data and to manage the table column properties.

3-41 Create the factory class TableModelFactory.

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the TableModelFactory class. Make the class public and include it in the
package com.sap.epf.ja200.exc.lab04.

Import the following classes/packages.
import javax.swing.*;
import javax.swing.table.*;
import com.sap.epf.ja100.model.*;
import com.sap.epf.ja100.util.*;
import com.sap.epf.ja100.persist.*;

Define the following methods (empty at first):
Modifier Return type Name/parameter list
public
static
AbstractTableModel createAbstractTableModel(
int busObjType )
public
static
DefaultTableColumnModel create
DefaultTableColumnMo
del ( int busObjType )
Line 1: Creates a valid TableModel.
Line 2: Creates a valid TableColumnModel.

SAP AG JA200 3-131
3-42 Implement the method(s):

public static abstractTableModel
createAbstractTable Model( int busObjType ) {
return new ATMVehicle();
}
The method returns a reference to an object of the inner class
TableFactory.ATMVehicle. You will later implement this inner class.


public static DefaultTableColumnModel
createDefaultTableColumnModel( int busObjType ) {
return new DTCMVehicle();
}
The method returns a reference to an object of the inner class
TableFactory.DTCMVehicle. You will later implement this inner class.

3-43 Implement the inner class.

private static class ATMVehicle
extends AbstractTableModel {
private static IPool vehiclePool;
private static String columnNames[] =
{
StaticGuiData.res.getRsrc("status"),
StaticGuiData.res.getRsrc("model"),
StaticGuiData.res.getRsrc("tag"),
StaticGuiData.res.getRsrc("mileage"),
StaticGuiData.res.getRsrc("lent"),
StaticGuiData.res.getRsrc("id"),
};

. . .
}
This class should be an inner class of the class
com.sap.epf.ja200.lab03.sol.TableFactory and should define the above
attributes.
Create the following constructor:
public ATMVehicle()
First, call the superclass constructor.
Get a reference to the com.sap.epf.ja100.persist.PersistManager using the
StaticData class.
Using the vehiclePool=(IPool)pManager.getBusObjectPool("vehicle"); statement,
create a reference to the vehicle data.
Provide the following methods:
public int getColumnCount()

SAP AG JA200 3-132
This method returns the number of columns (-> columnName.length )

public int getRowCount()
This method returns the number of data records in the vehicle pool.

public Object getValueAt(int row, int col)
This method returns the object (of data type VehicleRow) at the row/col position.

public Class getColumnClass( int col )
This method returns the data type of the specified column for example, Long.class or
Boolean.class.
3-44 Implement the inner class.

private static class DTCMVehicle
extends DefaultTableColumnModel
Make this class a subclass of DefaultTableColumnModel and an inner class of
com.sap.epf.ja200.lab03.sol.TableFactory.

Provide a default constructor: First, call the superclass constructor. Make the class
initialize the table column headers by looping through the content of
ATMVehicle.columnNames. Insert the following statements in the loop body:
TableColumn tabCol;
tabCol.setHeaderValue(ATMVehicle.columnNames[idx]);
this.addColumn(tabCol);
This statement sets the column headers.


SAP AG JA200 3-133
JFC: Swing Exercises 7-2


Unit: JFC: Swing
Topic: Swing GUI for the Car Rental Company,
Part 6-2

At the conclusion of this exercise, you will be able to:
Develop a component that provides a JTable for displaying the
vehicle data.

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 45. Take a look at the graphic(s).
JVIEWER

3-45 Create the class TablePanel
Stay in the package com.sap.epf.ja200.exc.lab03.
Define the class TablePanel. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab04.

Import the following classes/packages.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

Derive your class or implement the following interfaces.
extends JPanel

Define the following attributes:
Modifier Type Name
private GuiManager guiManager
private JTable table
private TableModel myTableModel
private DefaultTableColumnMo
del
myTableCol
private int busObjType
Line 5 is a flag that specifies the type of pool data such as StaticData.VEHICLE for
vehicle data.

SAP AG JA200 3-134
Define the following constructor (empty at first):
Modifier Name/parameter list
public TablePanel( GuiManager guiManager, int
busObjType )
This constructor takes as its arguments a reference to the GuiManager and a flag for the
type of pool data.

Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void initialize
Initializes the class.
3-46 Implement the method:

public void initialize()
Assign valid objects to the reference variables myColModel and myTableModel using
the TableFactory class.
Instantiate the table variable. When you call the constructor, use the myColModel and
myTableModel variables.
For the component, use a BorderLayout.
Assign the table to a JScrollPane and put it in the center of the component.

3-47 Implement the constructor:

public TablePanel( GuiManager guiManager,
int busObjType)
Pass these parameters to the object attributes.
Afterwards, call the initialize() method.

3-48 Register the TablePanel in the GuiManager class.
Open the GuiManager class. In the constructor, insert an instance of the class
TablePanel in the guiComponents hashtable using the following string as a key:
StaticGuiData.res.getRsrc("day"),
Verwenden Sie folgenden Konstruktoraufruf
new TablePanel(this, StaticData.VEHICLE)
3-49 Test the new component

Open the MainScreen class.
Add the following statements to the constructor:
cmpCenter = MainScreenWorkbench)guiManager.
getGuiComponent("MainScreen.Workbench");
String keyVehicles =
StaticGuiData.res.getRsrc( "vehicles" );
MainScreenWorkbench wb = (MainScreenWorkbench)cmpCenter;
wb.refreshContent( keyVehicles );



SAP AG JA200 3-135
JFC: Swing Exercises 7-3


Unit: JFC: Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 6-3

At the conclusion of this exercise, you will be able to:
React to user input to the JTable component using a controller.

Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 50. Take a look at the graphic(s).
JVIEWER

3-50 To enable users to edit the data, add a listener class to the TablePanel
component.
This class should be registered as a listener in the TablePanel class.
You will later add buttons to the TablePanel class, which users can choose to edit
the table data.

Create the class TableController.
Stay in the package com.sap.epf.ja200.exc.lab03.
Define the TableController class. Make the class public and include it in the
package com.sap.epf.ja200.exc.lab03.

Import the following classes/packages.
import com.sap.epf.ja100.model.*;
import com.sap.epf.ja100.cmd.CommandManager;
import com.sap.epf.ja100.util.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
Derive your class or implement the following interfaces.
implements IEventObserver, ActionListener

Define the following attributes:
Modifier Type Name
private CommandManager cmdMan
private JTable table
private int busObjType

SAP AG JA200 3-136
private String actionCmd
private int rowIdx
Line 1: The CommandManager is responsible for communicating with the data model.
This allows the model data and logic (inserting, deleting, and so on) to be separated
from the GUI, by means of encapsulation.
Line 3: The command sent from the buttons.

Define the following constructor (empty at first):
Modifier Name/parameter list
public TableController(JTable jTable, int busObjType)
Line 1 expects a reference to to the table and a flag that specified the data type used
(such as vehicle data, personal data, and so on).

Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void actionPerformed(ActionEvent
event)
private void
addTableRow() {
private void saveTableRow()
public void eventPerformed( EventObject
event )
Line 1: Called by JButton.
Line 2: Inserts a record in the model (delegates to the CommandManager)
Line 3: Makes the models state persistent (delegates to the CommandManager)
Line 4: Displays a dialog box when a record is inserted, allowing the user to enter the
new data. This is a callback method. As soon as the user confirms the entries by
choosing OK, the dialog box calls this method. The new data record can be accepted
and passed to the CommandManager to be processed.

3-51 Implement the method:

public void actionPerformed(ActionEvent event)
This method is called by the JButtons in the TablePanel. Call either
addTableRow() or saveTableRow() depending on the actionCommand
(StaticData.ACT_SAVE ).

You can copy the following methods from the template class
com.sap.epf.ja200.lab03.sol.TableController. For a description of these
methods, refer to the course material, solution 3-51.

private void addTableRow()

private void saveTableRow()
public void eventPerformed( EventObject event )


SAP AG JA200 3-137
3-52 Implement the constructor:
public TableController( JTable jTable, int busObjType )
Pass the parameters to the attributes with the same names in the controller class. Get the
CommandManager of the application (key cmd) from the class
com.sap.epf.ja100.util.StaticData.

3-53 To enable users to edit the data, add buttons to the component.

This function is already implemented in the template class.
Open the template class com.sap.epf.ja200.lab03.sol.TablePanel.

Search for the entry lab03 3-50 .
Copy the following four blocks of source code:
1. The import statements
The definition of a TableController reference variable
The statements at the end of the constructor
The private initializeToolbar method at the end of the class.
For a description of these methods, refer to the course materials, solution 3-53.
Compile and test your application.



SAP AG JA200 3-138
JFC: Swing Exercises 8-1


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 7

At the conclusion of this exercise, you will be able to:
Add a further component that aggregates a JTree to the vehicle
application.


Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 + 54. Take a look at the graphic(s).
JVIEWER

Note:
In the following exercises, you will develop a further component, step by step. This component
will aggregate the JTree class, and you will use it to navigate in the GUI.

3-54 Create the TreePanel component.

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the TreePanel class. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.

Import the following packages:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

Derive your class or implement the following interfaces.
extends Jpanel


SAP AG JA200 3-139
Define the following attributes:
Modifier Typ Name
private GuiManager guiManager
private JTree tree
private DefaultMutableTre
eNode
tnRoot,
tnMasterData,
tnBooking,
tnBookingList,
tnLeaf;
private DefaultTreeModel treeModel
private Vector masterData

Define the following constructor (empty at first):
Modifier Name/parameter list
public TreePanel(GuiManager guiManager)

Define the following methods (empty at first):
Modifier Return type Name/parameter list
private void createTreePanel()
Line 1: Creates the tree.

3-55 Implement the constructor.

public TreePanel(GuiManager guiManager)
Assign the parameter value to the same-name instance variable.
Instantiate the reference variable masterData and enter the node name of the tree there.
For this purpose, use the class StaticGuiData.res (language dependency!) again and
call its method getRsrc(...) using the strings vehicles, persons, address data, and
booking.
Call the method createTreePanel();

3-56 Implement the method(s):

private void createTreePanel()
Then, instantiate the reference variable tnMasterData. Implement a for loop in which
you iterate the content of masterData. Instantiate the reference variable tbLeaf in the
loop body by passing the current value of masterData during the constructor call
(careful: cast to string is necessary). Enter tbLeaf within the loop in tnMasterData.
Then, instantiate the reference variable tnRoot. For the constructor call, use the
statement StaticGuiData.res.getRsrc( "carControl"). Enter
tnMasterdata in tnRoot.
Then, instantiate the reference variable treeModel. For the constructor call, use tnRoot
as argument.
Then, instantiate the reference variable tree. For the constructor call, use treeModel as
argument.

SAP AG JA200 3-140
Set the following attributes:
1. The root entry should be visible.
2. The component should have FlowLayout.
3. Set the background color of the component to white.
4. Add the tree of the component.


3-57 Register the new component with the GuiManager.
Use the key Workbench.LaunchpadArea.Tree.

3-58 Add the new component to the MainScreenWorkbench class
Change the constructor of the MainScreenWorkbench class. Get the reference to the
TreePanel object using the GuiManager.
Assign this reference to the attribute pnlLaunchPadArea. Enter pnlLaunchPadArea into
a JSscrollPane. Add this in the left area of the MainScreenWorkbench.

Compile and test the application.


SAP AG JA200 3-141
JFC: Swing Exercises 8-2


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 7

At the conclusion of this exercise, you will be able to:
React to user input in the JTree component using the controller
class.


Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab03 59. Take a look at the graphic(s).
JVIEWER

3-59 To enable users to edit the data, add a listener class to the TreePanel component.
This class should be registered as a listener in the TreePanel class.
In this way, it is possible to react to user input in the JTree.

Create the TreeController class.
Stay in the package com.sap.epf.ja200.exc.lab03.
Define the TreeController class. Make the class public and include it in the
package com.sap.epf.ja200.exc.lab03.

Import the following classes/packages:
import com.sap.epf.ja100.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

Derive your class or implement the following interfaces.
implements TreeSelectionListener

Define the following attributes:
Modifier Type Name
private GuiManager guiManager
private Jtree jTree
private String actionCmd


SAP AG JA200 3-142
Define the following constructor (empty at first):
Modifier Name/parameter list
public public TreeController( JTree jTree )

Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void valueChanged(
TreeSelectionEvent event )
Line 1: This method is defined by the TreeSelectionListener interface.

3-60 Implement the constructor:

public TreeController( JTree jTree )
Assign the parameter to the same-name attribute.
Get a reference to the GuiManager from the class
com.sap.epf.ja100.util.StaticData and assign this reference to the
guiManager variable.

3-61 Implement the method(s):

public void valueChanged( TreeSelectionEvent event )
This method is called by the JTree class as soon as the user selects a TreeNode.
If the node you selected is a lower-level node of the node masterData (careful:
language-dependent), enter an appropriate component to the ContentArea of the class
MainScreenWorkbench (you will get the reference through the GuiManager).

3-62 Add the Controller class to the component TreePanel.
In the class TreePaneli, define a reference variable of the type TreeController.
Instantiate this variable in the constructor and register it with JTree of the TreePanel
component.

Compile and test the application.


SAP AG JA200 3-143
JFC: Swing Exercises 9


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 8

At the conclusion of this exercise, you will be able to:
Use a JEditorPane


Before you start:

In the following exercises, you will create a Help dialog, which users can call up using the
Help menu item. To do this, you use a JEditorPane, displayed using HTML pages.

4-63 Create the class DialogHelp

Stay in the package com.sap.epf.ja200.exc.lab03.
Define the DialogHelp class. Make the class public and include it in the package
com.sap.epf.ja200.exc.lab03.

Import the following packages:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.beans.*;

Derive your class or implement the following interfaces.
extends JDialog

Define the following attributes:
Modifier Type Name
private GuiManager guiManager
private JPanel pnlStatus,
pnlBrowser
private JEditorPane editorPane
private JScrollPane scrollPane
private JLabel lblStatus
private java.net.URL url
private String fileName


SAP AG JA200 3-144
Define the following constructor (empty at first):
Modifier Name/parameter list
public DialogHelp( GuiManager guiManger )


Define the following methods (empty at first):
Modifier Return type Name/parameter list
public void start( String title, String
filename );


4-64 Implement the constructor.

Help:
Start JViewer. In the directory tree, choose the node Exercises
+ lab04 64. Take a look at the graphic(s).
JVIEWER

public DialogHelp( GuiManager guiManager )
Create the dialog layout, using the layout in the above graphic as a guide.

4-65 Implement the method:

public void start( String title, String fileName )
Try to load the file fileName using the URL class.
Use the following statement:
try {
url = new java.net.URL( "file:///"+fileName );
editorPane.setPage( url );
} catch ( Exception exc ) {
exc.printStackTrace();
}
Set the modal and visible properties to true.
4-66 Insert the DialogHelp class in the GuiManager, using the MainScreen.Menu.Help
key.
4-67 Edit the class MainScreenMenu, using the MainScreen.Menu.Help key.
Add an ActionListener to the initialize() method of the variable mItemHelp.

mItemHelp.setActionCommand(
StaticGuiData.res.getRsrc( "helpTopics") );
mItemHelp.addActionListener( new MenuItemAction() );

SAP AG JA200 3-145
4-68 Edit the inner class MainScreenMenu.MenuItemAction.
StaticGuiData.res.getRsrc("helpTopics") ) ) {
String docuFile =
"C:\\JavaCourse\\GuiKit\\JA200.html";
DialogHelp dialogHelp
((DialogHelp)guiManager.getGuiComponent("MainScreen.Menu.H
elp"));
dialogHelp.start(
StaticGuiData.res.getRsrc("helpTopics"),
docuFile );}


SAP AG JA200 3-146
JFC, SWING Solutions 1


Unit: JFC, Swing
Topic: Component Development
3-1 Create the Jspinner class.

package com.sap.epf.ja200.sol.lab03;

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

public class JSpinner extends JComponent {
private JTextField textfield;
private int value, min, max;
private int adjustSize;
private JButton btnUp;
private JButton btnDown;

public JSpinner(int value, int min, int max,
int adjustSize ) {
}

private class LocalActionListener
implements ActionListener {
}

private class LocalKeyListener
implements KeyListener {
}

public int getValue() {
}

private void displayValue( int newValue ) {
}

public static void main(String argv[]) {

SAP AG JA200 3-147
}

}


SAP AG JA200 3-148
3-3 Implement the constructor.

. . .
public class JSpinner extends JComponent {
. . .
public JSpinner(int value, int min, int max,
int adjustSize ) {
super();
this.value = value;
this.min = min;
this.max = max;
this.adjustSize = adjustSize;

GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.NONE;

this.setLayout( gbl );
JPanel pnl = new JPanel();
pnl.setLayout( new BorderLayout() );
textfield = new JTextField( 10 );
textfield.setEditable(false);
textfield.setBorder(
BorderFactory.createEmptyBorder() );
textfield.addKeyListener(
new LocalKeyListener());
Dimension sizeText =
textfield.getPreferredSize();

int butWidth = 20;
int butHeight = sizeText.height/2 - 1;
JPanel pnlBut = new JPanel();
pnlBut.setLayout( new GridLayout(2,1) );
pnlBut.setPreferredSize(
new Dimension(butWidth, sizeText.height));
pnlBut.setBorder(
BorderFactory.createLineBorder(Color.black) );
btnUp = new JButton();

SAP AG JA200 3-149
btnUp.setActionCommand("increase");
btnUp.setToolTipText("increase");
btnUp.setPreferredSize( new
Dimension(butWidth, butHeight) );
btnUp.addActionListener( new
LocalActionListener() );
btnUp.addKeyListener( new
LocalKeyListener() );
btnUp.setBorder(BorderFactory.createLi
neBorder(Color.black));

btnDown = new JButton();
btnDown.setActionCommand("decrease");
btnDown.setToolTipText("decrease");
btnDown.setPreferredSize( new
Dimension(butWidth, butHeight) );
btnDown.addActionListener( new
LocalActionListener() );
btnDown.addKeyListener( new
LocalKeyListener() );
btnDown.setBorder(BorderFactory.createLi
neBorder(Color.black));

pnlBut.add( btnUp );
pnlBut.add( btnDown );

pnl.add( textfield, BorderLayout.CENTER );
pnl.add( pnlBut, BorderLayout.EAST );
pnl.setBorder( BorderFactory.createLi
neBorder(Color.black) );

this.add( pnl );

displayValue( value );
}
} // class JSpinner


SAP AG JA200 3-150
3-4 Implement the main method.
. . .
public class JSpinner extends JComponent {
. . .
public static void main(String argv[]) {
JFrame frame = new JFrame();
JPanel pnl = new JPanel();
pnl.setLayout( new BorderLayout() );
JSpinner spin = new JSpinner(40, 0, 100, 2);
pnl.add( spin, BorderLayout.CENTER );

frame.getContentPane().add( pnl );
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frame.pack();
frame.setTitle("JSpinner");
frame.setVisible(true);
}
}


SAP AG JA200 3-151
3-5 Implement the method displayValue(int newValue).
. . .
public class JSpinner extends JComponent {
. . .
private void displayValue( int newValue ) {
if(newValue<min) {
newValue = min;
} else if (newValue>max) {
newValue = max;
}
value = newValue;
textfield.setText(Integer.toString(value));
}
}


3-6 Implement the ButtonListener LocalActionListener as internal class.

. . .
public class JSpinner extends JComponent {
. . .
private class LocalActionListener
implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("increase") ) {
displayValue( getValue() + adjustSize );
} else if (e.getActionCommand().equals
("decrease") ) {
displayValue( getValue() - adjustSize );
}
}
}
}



SAP AG JA200 3-152
3-7 Implement the KeyListener LocalKeyListener as internal class.

. . .
public class JSpinner extends JComponent {
. . .
private class LocalKeyListener
implements KeyListener {
public void keyReleased( KeyEvent e ) {}
public void keyTyped( KeyEvent e ) {}
public void keyPressed( KeyEvent e ) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
displayValue( getValue() + adjustSize );
break;
case KeyEvent.VK_DOWN:
displayValue( getValue() - adjustSize );
break;
} // switch
}
}
}



SAP AG JA200 3-153
JFC, SWING Solutions 2


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 1
3-8 Create the main class CarControllApp.
package com.sap.epf.ja200.exc.lab03;

import com.sap.epf.ja100.app.*;
import com.sap.epf.ja100.cmd.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.util.*;
import java.util.*;

public class CarControlApp implements ICarControl {
// private PersistManager persistMan;
// private CommandManager cmdMan;
// private GuiManager guiMan;

public static void main(String[] args) {
}

private void setProperties() {
}

public CarControlApp() {
}

public void callBackFromLogon() {
}

}
3-9 Implement the method(s):

private void setProperties() {
try {
StaticData.setProperties (
com.sap.epf.ja200.app.CarControlApp.class,
"JA200.ini" );
} catch (Exception exc) {
System.out.println("Error loading Properties");
System.out.println(exc.getMessage());
}
}
3-10 Implement the constructor.

public CarControlApp() {
setProperties();
CSystem.init();
}

SAP AG JA200 3-154


3-11 Implement the main method.
public static void main( String args[] ) {
CarControlApp app = new CarControlApp();
}


3-13 Create the logon screen DialogLogon.

import com.sap.epf.ja100.app.ICarControl;
import com.sap.epf.ja100.util.IconFactory;
import javax.swing.*;

public class DialogLogon extends JDialog {
private JTextField txtUser;
private JPasswordField txtPassword;
private JComboBox cbLang;
private IconFactory.MultiIcon multiIcon;
private ICarControl icc;

public DialogLogon( ICarControl icc ) {}

private JPanel initWest() {
return new JPanel();
}

private JPanel initCenter() {
return new JPanel();
}

private JPanel initSouth() {
return new JPanel();
}

public void showIt() {}
}


SAP AG JA200 3-155
3-14 Implement the method(s):

private JPanel initWest() {
JPanel pnlWest = new JPanel();
multiIcon = StaticGuiData.iFac.getIcon( "ScrJA200" );
JLabel label = new JLabel(
multiIcon.getInitialScaled(160,160));
pnlWest.add( label );
return pnlWest;
}


3-15 Implement the method(s):

private JPanel initSouth() {
JPanel pnlSouth = new JPanel();
pnlSouth.setLayout(new
FlowLayout(FlowLayout.RIGHT));
JButton jbOk = new JButton(
StaticGuiData.res.getRsrc("ok"));
pnlSouth.add( jbOk );
JButton jbCnc = new JButton(
StaticGuiData.res.getRsrc("cancel") );
pnlSouth.add( jbCnc );
return pnlSouth;
}


3-16 Implement the method(s):

private JPanel initCenter() {
JPanel pnlCenter = new JPanel();
pnlCenter.setLayout( new GridLayout(6,2));
pnlCenter.setBorder( new
TitledBorder(StaticGuiData.res.getRsrc(
"logon data")) );

// username
pnlCenter.add(new
JLabel(StaticGuiData.res.getRsrc("user")));
txtUser = new JTextField();
pnlCenter.add( txtUser );

// password
pnlCenter.add(new
JLabel(StaticGuiData.res.getRsrc("password")));
txtPassword = new JPasswordField();
pnlCenter.add( txtPassword );

// language
pnlCenter.add(new
JLabel(StaticGuiData.res.getRsrc("language")));
Set sortedSet = new TreeSet();

SAP AG JA200 3-156
sortedSet.add(Locale.getDefault().
getDisplayLanguage());
sortedSet.add(Locale.ENGLISH.getDisplayLanguage());
sortedSet.add(Locale.FRANCE.getDisplayLanguage());
sortedSet.add(Locale.GERMAN.getDisplayLanguage());
cbLang = new JComboBox(sortedSet.toArray());
pnlCenter.add(cbLang);
return pnlCenter;
}
In this example, the combo box was not simply filled with strings, but the current language setting
was gotten from the system through the Local Object. (This is part of Java Course JA100, Topic
Internationalization.)
Afterwards, the ISO language abbreviations for French, German, and English are read by the
Local Object and placed in a TreeSet. In this way, you ensure that the current language of the user
appears first in the combo box and that there can be no duplicates.
3-17 Implement the method(s):

private void showIt() {
this.setSize(new Dimension( 380, 200 ));
Dimension dimension =
Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation( (dimension.width -
getSize().width) / 2,
(dimension.height -
getSize().height) / 2 );
this.setResizable(false);
this.setModal(true);
this.setVisible(true);
}
The setLocation method specifies the position on the desktop where the dialog is to appear.

SAP AG JA200 3-157
3-18 Implement the constructor.

public DialogLogon( ICarControl icc ) {
super(new JDialog(),
StaticGuiData.res.getRsrc("logon"));
this.icc = icc;
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(
initCenter(),BorderLayout.CENTER );
this.getContentPane().add(
initSouth(), BorderLayout.SOUTH );
this.getContentPane().add(
initWest(), BorderLayout.WEST );

}


SAP AG JA200 3-158
3-19 Define an internal class to react to the button events.
private class LocalButtonAction
implements ActionListener {
DialogLogon parent;
public LocalButtonAction( DialogLogon parent ) {
this.parent = parent;
}

public void actionPerformed( ActionEvent event) {
String cmd = event.getActionCommand();
if( cmd.equals(StaticGuiData.res.getRsrc( "ok")) ) {
Locale loc = null;
String lang = cbLang.getSelectedItem().toString();
if (lang.equals(
Locale.ENGLISH.getDisplayLanguage())
) {
loc = new Locale( Locale.ENGLISH.getLanguage(),
Locale.ENGLISH.getCountry() )
} else if (lang.equals(
Locale.FRENCH.getDisplayLanguage())
){
loc = new Locale( Locale.FRENCH.getLanguage(),
Locale.FRENCH.getCountry() );
} else if (lang.equals(
Locale.GERMAN.getDisplayLanguage()) ){
loc = new Locale( Locale.GERMAN.getLanguage(),
Locale.GERMAN.getCountry() );
}
Locale.setDefault(loc);
StaticGuiData.res = JA200Lang.getRsrcBundle();
icc.callBackFromLogon();
parent.dispose();
} else if( cmd.equals(
StaticGuiData.res.getRsrc( "cancel")) ) {
parent.dispose();
}
}
}


SAP AG JA200 3-159
3-20 Add the inner class LocalButtonAction to the buttons as Listener.

public JPanel initSouth() {
. . .
jbOk.addActionListener(new LocalButtonAction(this));
. . .
jbCnc.addActionListener(new LocalButtonAction(this));

}



SAP AG JA200 3-160
JFC, SWING Solutions 3


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 2
3-23 Create the GuiManager class.

package com.sap.epf.ja200.sol.lab03;

import com.sap.epf.ja100.util.*;
import com.sap.epf.ja100.app.*;
import java.util.*;

public class GuiManager implements IManager {
private Hashtable guiComponents;

public GuiManager() { }

public void registerManager() { }

public Object getGuiComponent( String key )
throws NullPointerException {
return null;
}
}


3-24 Implement the method(s):

public void registerManager() {
StaticData.registerManager("gui", this);
}

public Object getGuiComponent( String key )
throws NullPointerException {
Object obj = guiComponents.get( key );
if (obj == null) throw new NullPointerException();
return obj;
}


SAP AG JA200 3-161
3-25 Implement the constructor.
public GuiManager() {
registerManager();
guiComponents = new Hashtable();
}
3-26 Change the class CarControlApp.
public class CarCOntrolApp implement IcarControl {
private PersistManager persistMan;
private CommandManager cmdMan;
private GuiManager guiMan;

public void callBackFromLogon() {
persistMan = PersistManager.getInstance( null );
persistMan.loadBusObjects();
cmdMan = CommandManager.getInstance();
guiMan = new GuiManager();
}
}
Line 2: An instance of the PersistManager is created. This model was already used
in the basic course JA100 StartUp Kit. It also belongs to the manager classes, and
it is used to read data from the files and to create the corresponding objects for
the vehicle model (Factory Pattern) using special factories. This class, too, is
registered in the class com.sap.epf.ja100.app.StaticData. In a container, it
has all the vehicle model objects ready (similar to GuiManager). Line 4: The
CommandManager was also discussed in the course JA100 StartUp Kit. The
CommandManager takes on the controller task, that is, it takes commands from
the UI (deleting, changing, saving, and so on) and executes these for the
corresponding vehicle model objects. In this way, the model is separated from the
interface (View).



SAP AG JA200 3-162
JFC, SWING Solutions 4


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 3
3-27 Create the MainScreen class.

package com.sap.epf.ja200.sol.lab03;
import com.sap.epf.ja100.util.IconFactory;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MainScreen extends JFrame
implements WindowListener {
private GuiManager guiManager;
private Jcomponent cmpNorth, cmpCenter, cmpSouth;

public MainScreen( GuiManager guiManager ) {
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}

private JPanel createPnlNorth() {
return null;
}

private JPanel createPnlSouth() {
return null;
}

}

3-28 Implement the method(s):

public void windowClosing(WindowEvent e) {
System.exit(0);
}

private JPanel createPnlNorth() {
JPanel pnlN = new JPanel();
pnlN.setLayout( new BorderLayout() );
JLabel companyLabel = new JLabel();

SAP AG JA200 3-163
IconFactory.MultiIcon multiIcon =
StaticGuiData.iFac.getIcon( "Company" );
companyLabel.setIcon( multiIcon.getInitial() );
JLabel labCourse = new JLabel();
multiIcon = StaticGuiData.iFac.getIcon( "JA200" );
labCourse.setIcon( multiIcon.getInitial() );
labCourse.setBackground(Color.white);
pnlN.add( labCourse, BorderLayout.WEST );
pnlN.add( companyLabel, BorderLayout.EAST );
pnlN.setBackground( Color.white );
return pnlN;
}


private JPanel createPnlSouth() {
JPanel pnlS = new JPanel();
pnlS.setLayout(new FlowLayout(FlowLayout.RIGHT));
pnlS.add( StaticGuiData.pBar );
StaticGuiData.pBar.setBorderPainted( false );
StaticGuiData.pBar.setStringPainted( true );
return pnlS;
}


3-29 Implement the constructor.

public MainScreen( GuiManager guiManager ) {
super("Java @ SAP, JA200 Guikit");
this.guiManager = guiManager;
this.getContentPane().setLayout(new BorderLayout();
cmpNorth = createPnlNorth();
cmpSouth = createPnlSouth();

this.getContentPane().add( cmpNorth,
BorderLayout.NORTH );
this.getContentPane().add( cmpSouth,
BorderLayout.SOUTH );
this.setLocation( new Point(200,200) );
this.setSize( new Dimension(250,300) );
this.addWindowListener(this);
}


SAP AG JA200 3-164
3-30 Register the MainScreen in the GuiManager class.

public GuiManager() {
registerManager();
guiComponents = new Hashtable();
guiComponents.put("MainScreen", new MainScreen(this));
}


3-31 Start the main screen.
public void callBackFromLogon() {
System.out.println("CallBack");
persistMan = PersistManager.getInstance( null );
persistMan.loadBusObjects();
cmdMan = CommandManager.getInstance();
guiMan = new GuiManager();
JFrame mainScreen=
(JFrame)guiMan.getGuiComponent("MainScreen")
mainScreen.setVisible(true);
)



SAP AG JA200 3-165
JFC, SWING Solutions 5


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company, Part 4
3-32 Create the class MainScreenMenu
Menu items: File, Tools, Help
Menu item File: Menu subitem Exit
Menu item Tools: Menu subitem Look & Feel
Menu subitem Motif
Menu subitem Windows
Menu subitem Metal
Menu subitem Display Log File
Menu subitem Settings
Menu item Help: Menu subitem Documentation
Menu subitem About JA200

Step 1: Create the main body of the class
1 package com.sap.epf.ja200.sol.lab03;

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

4 public class MainScreenMenu {
5 private static GuiManager guiManager;
6 private JMenuBar menuBar;
7 private JMenu menuFile, menuTools,
8 menuTools_LF, menuHelp;
9 private JMenuItem mItemExit, mItemHelp,
10 mItemAbout, mItemSettings,
11 mItemLogFiles;
12 private ButtonGroup btnGroup_LF;
13 private JRadioButtonMenuItem
14 jRadio_LF_Motif, jRadio_LF_Win,
15 jRadio_LF_Metal;
16 private JSeparator j1stSeparator =
new JSeparator();
17
18
19 public MainScreenMenu( GuiManager guiManager ) {
20 }
21
22 public JMenuBar getMenuBar() {
23 return menuBar;
24 }
25 }
Lines 5-16: The required attributes
Line 19: The constructor receives a GuiManager reference
Lines 22-24: The get method returns the menu bar

SAP AG JA200 3-166
Step 2: Auxiliary method for creating the main menu with submenus

private void initialize() {
// Menu "File"
menuFile = new JMenu(
StaticGuiData.res.getRsrc("file") );
mItemExit = new JMenuItem(
StaticGuiData.res.getRsrc( "exit") );
menuFile.add( mItemExit );

These methods create the menu item File with the menu subitem Exit

// Menu "Help"
menuHelp = new JMenu(
StaticGuiData.res.getRsrc( "help") );
mItemHelp = new JMenuItem(
StaticGuiData.res.getRsrc("helpTopics"));
mItemAbout = new JMenuItem(
StaticGuiData.res.getRsrc( "about") );
menuHelp.add( mItemHelp );
menuHelp.add(j1stSeparator);
menuHelp.add( mItemAbout );

These statements create the menu item Help with subitems that are separated by a separator


// Menu "Tools"
menuTools = new JMenu(
StaticGuiData.res.getRsrc("tools") );
menuTools_LF = new JMenu(
StaticGuiData.res.getRsrc("lookNfeel") );
btnGroup_LF = new ButtonGroup();
jRadio_LF_Motif = new JRadioButtonMenuItem("Motif");
jRadio_LF_Win = new JRadioButtonMenuItem("Windows");
jRadio_LF_Metal = new JRadioButtonMenuItem("Metal");

btnGroup_LF.add(jRadio_LF_Motif);
btnGroup_LF.add(jRadio_LF_Win);
btnGroup_LF.add(jRadio_LF_Metal);
menuTools_LF.add(jRadio_LF_Motif);
menuTools_LF.add(jRadio_LF_Win);
menuTools_LF.add(jRadio_LF_Metal);

mItemLogFiles = new JMenuItem(
StaticGuiData.res.getRsrc( "logFiles") );
mItemSettings = new JMenuItem(
StaticGuiData.res.getRsrc( "settings") );
menuTools.add(menuTools_LF);
menuTools.add(mItemLogFiles);
menuTools.add(mItemSettings);
These statements create the menu item Tools with subitems.
The subitem Look & Feel is a menu entry and contains a selection list that must be grouped in a
ButtonGroup.


SAP AG JA200 3-167
menuBar.add( menuFile );
menuBar.add( menuTools );
menuBar.add( menuHelp );
}
At the end of the method, all submenus are added to the main menu.

Step 3: Create the constructor
public MainScreenMenu( GuiManager guiManager ) {
this.guiManager = guiManager;
menuBar = new JMenuBar();
initialize();
}
The guiManager attribute is instantiated, as is the main menu bar menuBar. Afterwards, the
initialize method is called.
3-33 Add the class to the GuiManager.

public GuiManager() {
registerManager();
guiComponents = new Hashtable();
guiComponents.put(
"MainScreen.Menu", new MainScreenMenu(this) );
guiComponents.put(
"MainScreen", new MainScreen(this) );
}


SAP AG JA200 3-168
3-34 Insert the menu in MainScreen

public MainScreen( GuiManager guiManager ) {
super("Java @ SAP, JA200 Guikit");
this.guiManager = guiManager;
this.getContentPane().setLayout( new BorderLayout() );
pnlNorth = createPnlNorth();
pnlSouth = createPnlSouth();
mainScreenMenu = (MainScreenMenu)
guiManager.getGuiComponent(
"MainScreen.Menu");
this.setJMenuBar( mainScreenMenu.getMenuBar() );
. . .

In the MainScreen class, define a local class that can be added to the menu items
as a listener.

. . .
import java.awt.event.*;

public class MainScreenMenu {

. . .

public static class MenuItemAction
implements ActionListener {
public void actionPerformed( ActionEvent event ) {
String actionCmd = event.getActionCommand();
if( actionCmd.startsWith(
StaticGuiData.res.getRsrc("about") ) ) {
StaticGuiData.showAboutInformation();
}
}
} // inner class
}

Note the import statement.
The class must be registered as a listener for the menu item Help -> About JA200.

mItemAbout = new JMenuItem(
StaticGuiData.res.getRsrc( "about") );
mItemAbout.setActionCommand(
StaticGuiData.res.getRsrc( "about") );
mItemAbout.addActionListener( new MenuItemAction() );

3-36 Change the Look & Feel of the interface for the menu item Tools -> Look & Feel.

. . .
import java.awt.event.*;

public class MainScreenMenu {
. . .
private void initialize() {

SAP AG JA200 3-169
. . .
jRadio_LF_Motif = new JRadioButtonMenuItem("Motif");
jRadio_LF_Motif.setActionCommand( "LF_Motif" );
jRadio_LF_Motif.addActionListener(
new MenuItemAction() );
jRadio_LF_Win = new JRadioButtonMenuItem("Windows");
jRadio_LF_Win.setActionCommand( "LF_Windows" );
jRadio_LF_Win.addActionListener(
new MenuItemAction() );
jRadio_LF_Metal = new JRadioButtonMenuItem("Metal");
jRadio_LF_Metal.setActionCommand( "LF_Metal" );
jRadio_LF_Metal.addActionListener(
new MenuItemAction() );
. . .
}
}

The local listener class is registered with the menu items.

. . .
import java.awt.event.*;

public class MainScreenMenu {

. . .

public static class MenuItemAction
implements ActionListener {
public void actionPerformed( ActionEvent event ) {
String actionCmd = event.getActionCommand();
if( actionCmd.startsWith(
StaticGuiData.res.getRsrc("about") ) ) {
StaticGuiData.showAboutInformation();

} else if( actionCmd.startsWith("LF_")) {
guiManager.setLF( actionCmd );
}
}
} // inner class
}
3-37 Implement the method(s):

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

public class GuiManager implements IManager {
private String lookAndFeel, plaf;
. . .

public void setLF( String laf ) {
setPlaf( laf );
setLF();
}

SAP AG JA200 3-170

private void setPlaf( String laf ) {
lookAndFeel = laf;
if ( lookAndFeel.equals("LF_Metal") ) {
plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if ( lookAndFeel.equals("LF_Motif") ) {
plaf = "com.sun.java.swing.
plaf.motif.MotifLookAndFeel";
} else if ( lookAndFeel.equals("LF_Windows") ) {
plaf = "com.sun.java.swing.
plaf.windows.WindowsLookAndFeel";
}
}

private void setLF() {
try {
UIManager.setLookAndFeel( plaf );
Enumeration enum = guiComponents.elements();
while( enum.hasMoreElements() ) {
try {
Component c =(Component)enum.nextElement();
SwingUtilities.updateComponentTreeUI( c );
} catch (Exception exc) {}
}
} catch (Exception exc1) {
System.err.println( exc1.getMessage() );
}
}
}



SAP AG JA200 3-171
JFC: Swing Solutions


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 5
3-38 Create the class MainScreenWorkbench

package com.sap.epf.ja200.sol.lab03;

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

public class MainScreenWorkbench extends JSplitPane {
private static GuiManager guiManager;
private JPanel pnlLaunchpadArea, pnlContentArea;

public MainScreenWorkbench( GuiManager guiManager ) {
super();
this.guiManager = guiManager;

pnlLaunchpadArea = new JPanel();
JScrollPane scr = new JScrollPane();
scr.setViewportView( pnlLaunchpadArea );

pnlContentArea = new JPanel();

this.setLeftComponent( scr );
this.getLeftComponent().setBackground(
Color.lightGray);
this.setRightComponent( pnlContentArea );
this.getRightComponent().setBackground(
Color.darkGray);
this.setDividerLocation( 150 );
this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.setOneTouchExpandable( true );
this.setOpaque(false);
}
}



SAP AG JA200 3-172

3-39 Register the new component with the GuiManager

public GuiManager() {
registerManager();
guiComponents = new Hashtable();
guiComponents.put("MainScreen.Workbench",
new MainScreenWorkbench(this));
guiComponents.put("MainScreen.Menu",
new MainScreenMenu(this));
guiComponents.put("MainScreen",
new MainScreen(this) );
}


Add the new component to the MainScreen class

public MainScreen( GuiManager guiManager ) {
super("Java @ SAP, JA200 Guikit");
this.guiManager = guiManager;
this.getContentPane().setLayout( new BorderLayout() );

cmpNorth = createPnlNorth();
cmpSouth = createPnlSouth();
cmpCenter = (MainScreenWorkbench)guiManager.
getGuiComponent( "MainScreen.Workbench" );

. . .



SAP AG JA200 3-173
3-40 Extend the MainScreenWorkbench class

import java.util.*;
. . .

public class MainScreenWorkbench extends JSplitPane {
. . .
private JTabbedPane tabbedPane;
private Vector guiComponentKeys;

public MainScreenWorkbench( GuiManager guiManager ) {
. . .
pnlContentArea = new JPanel();

guiComponentKeys = new Vector();
tabbedPane = new JTabbedPane();
pnlContentArea.add(tabbedPane);
. . .
}

public void refreshContent( String newContent ) {
this.setDividerLocation( 150 );
String guiComponentKey = "Workbench.ContentArea.";
Component guiComponent = (Component)new JPanel();
try {
guiComponent =
(Component)guiManager.getGuiComponent(
guiComponentKey+newContent);
} catch (Exception exc) { exc.printStackTrace(); }

if( !guiComponentKeys.contains(newContent) ) {
guiComponentKeys.add(newContent);
tabbedPane.addTab(newContent, guiComponent);
}
int idx = guiComponentKeys.indexOf(newContent);
tabbedPane.setSelectedIndex(idx);
this.setRightComponent( tabbedPane );
}
}



SAP AG JA200 3-174
JFC: Swing Solutions 7-1


Unit: JFC, Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 6-1
3-41 Create the factory class TableModelFactory.


package com.sap.epf.ja200.sol.lab03;
import javax.swing.*;
import javax.swing.table.*;
import com.sap.epf.ja100.model.*;
import com.sap.epf.ja100.util.*;
import com.sap.epf.ja100.persist.*;

public class TableModelFactory {

public static AbstractTableModel
createAbstractTableModel( int busObjType ) {
return new ATMVehicle();
}

public static DefaultTableColumnModel
createDefaultTableColumnModel( int busObjType ) {
return new DTCMVehicle();
}

private static class DTCMVehicle
extends DefaultTableColumnModel {
}

private static class ATMVehicle
extends AbstractTableModel {
}
}


SAP AG JA200 3-175

3-43 Implement the inner class.

public class TableModelFactory {

. . .

private static class ATMVehicle
extends AbstractTableModel {
private static IPool vehiclePool;
private static String columnNames[] =
{
StaticGuiData.res.getRsrc("status"),
StaticGuiData.res.getRsrc("model"),
StaticGuiData.res.getRsrc("tag"),
StaticGuiData.res.getRsrc("mileage"),
StaticGuiData.res.getRsrc("lent"),
StaticGuiData.res.getRsrc("id"),
};

public ATMVehicle() {
super();
try {
PersistManager pManager =
(PersistManager)StaticData.
getManager("persist");
vehiclePool = (IPool)pManager.
getBusObjectPool("vehicle");
} catch ( NullPointerException exc ) {
exc.printStackTrace();
}
}

public int getColumnCount() {
return columnNames.length;
}

public int getRowCount() {
return vehiclePool.getPoolSize();
}

public Object getValueAt(int row, int col) {

SAP AG JA200 3-176
VehicleRow vehicleRow =
(VehicleRow)vehiclePool.getRow(row);
switch(col) {
case 0:
return vehicleRow.getBusObjUpdateFlag();
case 1:
return vehicleRow.getVehicle().getVhclModel();
case 2:
return
vehicleRow.getVehicle().getVhclTag();
case 3:
return new
Long(vehicleRow.getVehicle().getVhclMileage());
case 4:
return new
Boolean(vehicleRow.getVehicleLent());
case 5:
return vehicleRow.toString();
}
return null;
}

public Class getColumnClass( int col ) {
switch(col) {
case 3: return Long.class;
case 4: return Boolean.class;
}
return String.class;
}
} // inner class
} // class TableModelFactory



SAP AG JA200 3-177
3-44 Implement the inner class.

public class TableModelFactory {
: : .

private static class DTCMVehicle
extends DefaultTableColumnModel {
public DTCMVehicle() {
super();
for( int idx = 0;
idx < ATMVehicle.columnNames.length;
idx++ ) {
TableColumn tabCol;
tabCol.setHeaderValue(
ATMVehicle.columnNames[idx]);
this.addColumn(tabCol);
}
}
} // inner class
}



SAP AG JA200 3-178
JFC: Swing Solutions 7-2


Unit: JFC, Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 6-2

3-45 Create the class TablePanel

1 package com.sap.epf.ja200.sol.lab03;
2 import java.awt.*;
3 import javax.swing.*;
4 import javax.swing.table.*;
5 import java.util.*;

6 public class TablePanel extends JPanel {
7 private GuiManager guiManager;
8 private JTable table;
9 private TableModel myTableModel;
10 private DefaultTableColumnModel myColModel;
11 private int busObjType;

12 public TablePanel( GuiManager guiManager,
13 int busObjType ) {
14 this.guiManager = guiManager;
15 this.busObjType = busObjType;
16 initialize();
17 }

18 public void initialize() {
19 myTableModel = TableModelFactory.
20 createAbstractTableModel(busObjType);
21 myColModel = TableModelFactory.
22 createDefaultTableColumnModel(busObjType);

23 table = new JTable(myTableModel,myColModel);
24 table.setAutoResizeMode(
25 JTable.AUTO_RESIZE_LAST_COLUMN);
26 table.setSelectionBackground(Color.blue);
27 table.setSelectionForeground(Color.white);
28 table.setSelectionMode(

SAP AG JA200 3-179
29 ListSelectionModel.SINGLE_SELECTION);
30 this.setLayout(new BorderLayout());
31 JScrollPane scr = new JScrollPane();
32 scr.setViewportView( table );
33 this.add(scr, "Center");
34 }
35 }
Line 19-22: The table model is initialized.
Line 23: An instance of JTable is created with a table model and column model.
Line 24-29: Optional settings for table display.
Line 31-32: JTable is embedded in JScrollPane.

3-48 Register the TablePanel in the GuiManager class.

public GuiManager() {
registerManager();
guiComponents = new Hashtable();

String keyVehicles =
"Workbench.ContentArea." +
StaticGuiData.res.getRsrc( "vehicles" );
guiComponents.put( keyVehicles,
new TablePanel(this, StaticData.VEHICLE) );

guiComponents.put("MainScreen.Workbench",
new MainScreenWorkbench(this));
guiComponents.put("MainScreen.Menu",
new MainScreenMenu(this));
guiComponents.put("MainScreen",
new MainScreen(this) );
}


SAP AG JA200 3-180
3-49 Test the new components
Open the class MainScreen. Add the following statements to the constructor:
public MainScreen( GuiManager guiManager ) {
super("Java @ SAP, JA200 Guikit");
this.guiManager = guiManager;
this.getContentPane().setLayout( new BorderLayout() );
cmpNorth = createPnlNorth();
cmpSouth = createPnlSouth();
cmpCenter = (MainScreenWorkbench)guiManager.
getGuiComponent("MainScreen.Workbench");

String keyVehicles = StaticGuiData.res.getRsrc(
"vehicles" );
MainScreenWorkbench wb =
(MainScreenWorkbench)cmpCenter;
wb.refreshContent( keyVehicles );
. . .
}



SAP AG JA200 3-181
JFC: Swing Solutions 7-3


Unit: JFC, Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 6-3

3-50 To enable users to edit the data, add a listener class to the TablePanel
component. Create the TableController class.

package com.sap.epf.ja200.sol.lab03;

import com.sap.epf.ja100.model.*;
import com.sap.epf.ja100.cmd.CommandManager;
import com.sap.epf.ja100.util.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

import com.sap.epf.ja200.gui.DialogBusObjects;

public class TableController
implements IEventObserver, ActionListener {
private JTable table;
private CommandManager cmdManager;
private int busObjType;
private String actionCmd;
private int rowIdx;

public TableController( JTable jTable,
int busObjType ) {
}

public void actionPerformed(ActionEvent event) {
}

private void addTableRow() {
}


SAP AG JA200 3-182
private void saveTableRow() {
}

public void eventPerformed( EventObject event ) {
}

}


3-51 Implement the method(s):

public void actionPerformed(ActionEvent event) {
actionCmd = event.getActionCommand();
if (actionCmd.equals(StaticData.ACT_SAVE)) {
saveTableRow();
} else if(actionCmd.equals(StaticData.ACT_ADD_CAR)) {
addTableRow();
} else if(actionCmd.equals(StaticData.ACT_ADD_TRUCK)) {
addTableRow();
}
}


SAP AG JA200 3-183

private void addTableRow() {
rowIdx = -1;
IBusObject busObjectRow =
cmdManager.createBusObjectRow(
busObjType, actionCmd, rowIdx );
DialogBusObjects tableDialog =
new DialogBusObjects(
StaticGuiData.res.getRsrc("add") );
tableDialog.setContent( busObjectRow );
tableDialog.attachObserver( this );
tableDialog.setModal(true);
tableDialog.setVisible( true );
This method first calls the CommandManager, which creates a default object of the
class specified by the value of the busObjType flag (for example, vehicle or person).
The reference to this object (of the predefined type DialogBusObjects) is passed to
the input dialog tableDialog). The controller class is registered as a listener with this
dialog, which is displayed in a modal window on the desktop.



private void saveTableRow() {
cmdManager.createCommandStack( actionCmd );
cmdManager.processCommandStack();
AbstractTableModel aTabModel =
(AbstractTableModel)table.getModel();
aTabModel.fireTableDataChanged();
}
This method first calls the CommandManager. The Save event is stored as a command
on an internal stack, which is then processed by the following program statements. The
CommandManager makes all the model data persistent in files using the
PersistManager. The table must be refreshed for the changes to be visible.



SAP AG JA200 3-184

public void eventPerformed( EventObject event ) {
Object obj = event.getSource();
if ( obj instanceof
DialogBusObjects.DialogBusObjectsAction ) {
// Table-Dialog wurde beendet
DialogBusObjects.DialogBusObjectsAction

tableAction=
(DialogBusObjects.DialogBusObjectsAction)obj;

String action =
tableAction.getActionEvent().getActionCommand();

IBusObject busObjectRow =
tableAction.getBusObjectRow();

if ( action.startsWith( StaticData.ACT_OK ) ) {
cmdManager.createCommandStack( actionCmd );
cmdManager.processCommandStack();
AbstractTableModel aTabModel =
(AbstractTableModel)table.getModel();
aTabModel.fireTableRowsUpdated(rowIdx,rowIdx);
}
}
}
This method is called by the dialog as soon as the user chooses OK. The data input by the user can be
queried using the event object DialogBusObjectsAction sent by the dialog. The
CommandManager then resumes processing and adds the data to the appropriate pool.
3-52 Implement the constructor:

public TableController(JTable jTable, int busObjType) {
this.table = jTable;
this.busObjType = busObjType;
try {
cmdManager =
(CommandManager)StaticData.getManager("cmd");
} catch ( NullPointerException exc ) {
exc.printStackTrace();
}
}



SAP AG JA200 3-185
3-53 To enable users to edit the data, add buttons to the jTablePanel component.

import java.awt.event.*;
import javax.swing.event.*;
import com.sap.epf.ja100.util.*;

public class TablePanel extends JPanel {
. . .
private TableController tableController;
. . .

public TablePanel( GuiManager guiManager,
int busObjType ) { ... }

public void initialize() {
. . .
tableController = new TableController(table,
busObjType );
JToolBar toolbar = new JToolBar();
this.add( toolbar, "North");
initializeToolBar( toolbar );
}

. . .
private void initializeToolBar( JToolBar toolbar ) {
String[] btnToolTips = null;
String[] btnCmds = null;
IconFactory.MultiIcon multiIcons[] = null;

if( busObjType == StaticData.VEHICLE ) {
btnToolTips = new String[] {...};
multiIcons = new IconFactory.MultiIcon[] {...};
btnCmds = new String[] {...};
} else {
. . .
}
for (int idx = 0; idx < btnToolTips.length; idx++) {
JButton button = new JButton();
button.setBorderPainted(false);
IconFactory.MultiIcon multiIcon = multiIcons[idx];
button.setIcon((ImageIcon)multiIcon.
getInitialScaled(23,23));

SAP AG JA200 3-186
button.setActionCommand( btnCmds[ idx] );
button.setToolTipText( btnToolTips[idx]);
button.addActionListener( tableController );
button.addMouseListener( new LocalMouseListener(
button, multiIcon ) );
toolbar.add(button);
}
}
The initializeToolbar method instantiates several String arrays for the (language-specific) tooltips,
commands, and icons that you will be using. The buttons are created and added to the JToolbar in a
loop. The TableController class, which we created previously, is entered as an EventListener. So
that the program can react when the mouse cursor moves over a button, the inner class
LocalMouseListener is added as a MouseListener.

private class LocalMouseListener
extends MouseAdapter {
JButton button;
IconFactory.MultiIcon multiIcon;

public LocalMouseListener( JButton button,
IconFactory.MultiIcon multiIcon ) {
this.button = button;
this.multiIcon = multiIcon;
}

public void mouseEntered(MouseEvent e) {
button.setIcon((ImageIcon)
multiIcon.getSelectedScaled(23,23));
}

public void mouseExited(MouseEvent e) {
button.setIcon((ImageIcon)
multiIcon.getInitialScaled(23,23));
}
}





SAP AG JA200 3-187
JFC: Swing Solutions 8-1


Unit: JFC, Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 7-1

3-54 Create the TreePanel component.

package com.sap.epf.ja200.sol.lab03;

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


public class TreePanel extends JPanel {
private GuiManager guiManager;
private JTree tree;
private DefaultMutableTreeNode
tnRoot,
tnMasterData, tnBooking,
tnBookingList, tnLeaf;
private DefaultTreeModel treeModel;
private Vector masterData;

public TreePanel(GuiManager guiManager) {
}

private void createTreePanel() {
}

}


SAP AG JA200 3-188
3-55 Implement the constructor.

. . .
public class TreePanel extends JPanel {
. . .

public TreePanel(GuiManager guiManager) {
this.guiManager = guiManager;
masterData = new Vector();
masterData.add(
StaticGuiData.res.getRsrc("vehicles") );
masterData.add(
StaticGuiData.res.getRsrc("persons") );
masterData.add(
StaticGuiData.res.getRsrc("address data") );
masterData.add(
StaticGuiData.res.getRsrc("bookings") );
createTreePanel();
}

private void createTreePanel() {
}

}



SAP AG JA200 3-189
3-56 Implement the method(s):

. . .
public class TreePanel extends JPanel {
. . .

private void createTreePanel() {
tnMasterData = new DefaultMutableTreeNode(
StaticGuiData.res.getRsrc("masterData") );
for (int idx = 0; idx < masterData.size(); idx++ ) {
tnLeaf = new DefaultMutableTreeNode(
(String)masterData.get(idx) );
tnMasterData.add( tnLeaf );
}
tnRoot = new DefaultMutableTreeNode(
StaticGuiData.res.getRsrc( "carControl") );
tnRoot.add( tnMasterData );

treeModel = new DefaultTreeModel(tnRoot);
tree = new JTree( treeModel )
tree.setRootVisible( true );

this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.add(tree);
this.setBackground(Color.white);
}
}
3-57 Register the new component with the GuiManager

public GuiManager() {
registerManager();
guiComponents = new Hashtable();
guiComponents.put("Workbench.LaunchpadArea.Tree",
new TreePanel(this));
guiComponents.put("MainScreen.Workbench",
new MainScreenWorkbench(this));
guiComponents.put("MainScreen.Menu",
new MainScreenMenu(this));
guiComponents.put("MainScreen",
new MainScreen(this));
}



SAP AG JA200 3-190
3-58 Add the new component to the MainScreenWorkbench class.

public MainScreenWorkbench( GuiManager guiManager ) {
super();
this.guiManager = guiManager;

TreePanel pnlTree =
(TreePanel)guiManager.getGuiComponent(
"Workbench.LaunchpadArea.Tree");
pnlLaunchpadArea = pnlTree;
JScrollPane scr = new JScrollPane();
scr.setViewportView( pnlLaunchpadArea );

pnlContentArea = new JPanel();
guiComponentKeys = new Vector();
tabbedPane = new JTabbedPane();
pnlContentArea.add(tabbedPane);

this.setLeftComponent( scr );
this.setRightComponent( pnlContentArea );
this.setDividerLocation( 150 );
this.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
this.setOneTouchExpandable( true );
this.setOpaque(false);
}



SAP AG JA200 3-191
JFC: Swing Solutions 8-2


Unit: JFC, Swing
Topic: Swing GUI for the Vehicle Rental Company,
Part 7-2

3-59 Create the TreeController class.

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

public class TreeController
implements TreeSelectionListener {

private GuiManager guiManager;
private JTree jTree;
private String actionCmd;

public TreeController( JTree jTree ) {
}

public void valueChanged( TreeSelectionEvent event ) {
}
}



SAP AG JA200 3-192
3-60 Implement the constructor:

. . .
public TreeController( JTree jTree ) {
super();
this.jTree = jTree;
try {
guiManager =
(GuiManager)StaticData.getManager("gui");
} catch ( NullPointerException exc ) {
exc.printStackTrace();
}
}
. . .



SAP AG JA200 3-193
3-61 Implement the method(s):

1 public void valueChanged(TreeSelectionEvent event) {
2 TreePath tp = event.getNewLeadSelectionPath();

3 if (tp != null) {
4 String node =
5 tp.getLastPathComponent().toString();

6 if( tp.getLastPathComponent()
instanceof TreeNode ) {
7 TreeNode treeNode =
(TreeNode)tp.getLastPathComponent();
8 String treeNodeParent =
treeNode.getParent().toString();
9 if( treeNodeParent.equals(
StaticGuiData.res.getRsrc("masterData")) ) {
10 MainScreenWorkbench wb =
(MainScreenWorkbench)
guiManager.getGuiComponent(
"MainScreen.Workbench");
11 wb.refreshContent( node );
12 }
13 }
14 }
15 }
Line 2: A TreePath instance is created through the event variable.
Line 3: If this is not null:
Line 4: The name of the selected node is read.
Line 5: If this is a Tree node...
Line 6: Access to the TreeNode instance and, using its method
Zeile 8: getParent().toString(), to the name of the superior node.
Line 9: If the name of the superior node is MasterData...
Line 10: Get a reference to MainScreenWorkbench and, using this, call the method
refreshContent.



SAP AG JA200 3-194
3-62 Add the Controller class to the component TreePanel.
public class TreePanel extends JPanel {
. . .
private TreeController treeController;

public TreePanel(GuiManager guiManager) {
. . .
createTreePanel();

treeController = new TreeController( tree );
tree.addTreeSelectionListener( treeController );
}
. . .
}



SAP AG JA200 3-195
JFC: Swing Solutions


Unit: JFC, Swing
Topic: Swing GUI for the Car Rental Company,
Part 8
2. 4-63 Create the class DialogHelp

package com.sap.epf.ja200.sol.lab03;
import com.sap.epf.ja100.util.IEventObserver;

public class DialogHelp extends JDialog {
private GuiManager guiManager;
private JPanel pnlStatus;
private JPanel pnlBrowser;
private JEditorPane editorPane;
private JScrollPane scrollPane;
private JLabel lblStatus;
private java.net.URL url;
private String fileName;

public DialogHelp(GuiManager guiManager) {
}

public void start( String title, String fileName ) {
}

private boolean visitUrl( java.net.URL url ) [
}
}




SAP AG JA200 3-196
4-64 Implement the constructor.

class DialogHelp extends JDialog {
. . .
public DialogHelp(GuiManager guiManager) {
super();
this.guiManager = guiManager;
pnlBrowser = new JPanel();
pnlBrowser.setLayout( new BorderLayout() );
pnlStatus = new JPanel();
pnlStatus.setLayout( new FlowLayout(
FlowLayout.RIGHT ) );
lblStatus = new JLabel();
pnlStatus.add( lblStatus );
scrollPane = new JScrollPane();
editorPane = new JEditorPane();
editorPane.setEditable( false );
scrollPane.setViewportView( editorPane );
pnlBrowser.add( scrollPane, BorderLayout.CENTER );
pnlBrowser.add( pnlStatus, BorderLayout.SOUTH );
this.getContentPane().add(pnlBrowser);
this.setSize(new Dimension( 550, 250 ));
Dimension dimension =
Toolkit.getDefaultToolkit().getScreenSize();
setLocation(
(dimension.width-getSize().width)/2,
(dimension.height-getSize().height)/2
);
}
. . .
}


4-65 Implement the method(s):

. . .
public void start( String title, String fileName ) {
this.setTitle( title );
if( this.fileName == null ||
!this.fileName.equals(fileName) ) {
this.fileName = fileName;
lblStatus.setText(fileName);
try {
url = new java.net.URL( "file:///"+fileName );
editorPane.setPage( url );
} catch ( Exception exc ) {
exc.printStackTrace(); }
}
this.setModal(true);
this.setVisible(true);
}
. . .



SAP AG JA200 4-1
SAP AG 2003
SWT (Standard Widget Toolkit)
l Installation
l Special features compared with AWT/Swing
Contents:




SAP AG JA200 4-2
SAP AG 2003
Introduction
Preface
AWT
Course Overview Diagram
Swing
Browser-Based GUI Development
SWT




SAP AG JA200 4-3
SAP AG 2003
Unit Objectives
At the conclusion of this unit, you will be able to:
l Describe GUI development using Eclipse SWT




SAP AG JA200 4-4
SAP AG 2003
Reasons for Using SWT
The project SWT ("Standard Widget Toolkit") was started for
developing the workbench of the development platform
"Eclipse"
GUIs created using SWT can make use of many resources
specific to the operating system
The graphical interfaces created using AWT or Swing are not
accepted by many developers because
- These GUIs are too different from the other programs on the
relevant operating system ("look")
- The behavior ("feel") of individual graphical components
does not meet expectations
- The possibilities specific to the operating system are not
supported



n SWT, Standard Widget Toolkit
When developing Eclipse, it was very important that the product was accepted by the user. Since
graphical interfaces created with AWT or Swing behave differently than other programs on the
relevant platform, particularly with regards to "feel"
(for example, different behavior when scrolling, opening menus, delays with certain actions, and so
on), the developers decided to make as much use as possible of the "native widgets" of the relevant
operating system for the graphical interface of Eclipse (the workbench).

For this purpose, the SWT project was initiated.

SAP AG JA200 4-5
SAP AG 2003
Installation
SWT consists of a Java section (swt.jar) and a library
implemented in C
Both parts are in the plugins directory of the Eclipse
installation



n Installation
To implement an SWT application you require both the relevant C library and the corresponding .jar
file. Both files can be found in the plugins directory of your Eclipse installation.

You either copy the Java archive to the ext directory of your JDK or JRE, or you add it (as shown
above for Eclipse) to the classpth explicitly when translating/executing in the relevant workbench.

The C-DLL must either be included in the call path of the operating system or you can specify it
explicitly as a parameter when calling your application:
java java.library.path=...

SAP AG JA200 4-6
SAP AG 2003
Comparison of SWT and Swing Classes
SWT Swing
01 Button JButton, JRadioButton, JCheckBox, JToggleButton
02 Canvas JPanel bzw. JComponent
03 Carret javax.swing.text.Carret
04 Combo JComboBox
05 Composite JPanel bzw. JScrollPane
06 Coolbar/-item -
07 Group JPanel mit TitledBorder
08 Label JLabel
09 List JList
10 Menu JMenuBar, JMenu, JPopupMenu
11 MenuItem JMenuItem
12 ProgressBar JProgressBar
13 Sash (JSplitPane)
14 Scale JSlider



Line 01: Clickable button
Line 02: Canvas, for painting your own control elements, for example
Line 03: Blinking cursor, for example for text input
Line 04: Combination of input field and list field
Line 05: Container for additional components
Line 06: Grouping of standard toolbar elements
Line 07: Container (with frame and title) for other components
Line 08: Text or graphic
Line 09: List field
Line 10: Menu bar, menu, or submenu
Line 11: Menu entry
Line 12: Progress display
Line 13: Movable separator between two components
Line 14: Control element for displaying or entering numbers





SAP AG JA200 4-7
SAP AG 2003
Comparison of SWT and Swing Classes (2)
SWT Swing
15 ScrollBar JScrollBar
16 Shell JWindow, JFrame nzw. JDialog
17 Slider JScrollBar
18 TabFolder JTabbedPane
19 TabItem (JPanel)
20 Table (JTable)
21 TableColumn
22 TableItem
23 Text JTextField, JPasswordField, JTextArea
24 ToolBar JToolBar
25 ToolItem
26 Tracker -
27 Tree (JTree)
28 TreeItem



Line 15: Separate, horizontal, or vertical scroll bar
Line 16: Dialog or window
Line 17: Control element for displaying or entering numbers
Line 18: Used for displaying tab pages
Line 19: Single element of a TabFolder
Line 20: Table of columns/rows for displaying texts or graphics
Line 21: Description of a table column
Line 22: Description of a table row
Line 23: Text input field consisting of one or several rows
Line 24: Standard toolbar
Line 25: Toolbar element
Line 26: Movable selection frame (no equivalent in Swing)
Line 27: Tree for displaying hierarchical data structures (texts and screens)
Line 28: Tree element





SAP AG JA200 4-8
SAP AG 2003
Special Features
Resource management
Unlike AWT/Swing, the developer has to take care of the
resource management himself/herself and cannot, for
example, rely on the garbage collection
LayoutManager
...
1 Display disp = new Display();
2 Shell shell = new Shell( disp );
3 shell.setLayout( new GridLayout() );
4 Button btn = new Button( shell, SWT.PUSH );
5 GridData grd = new GridData();
6 grd.horizontalAlignment = GridData.fill;
7 btn.setLayoutData( grd );
...



n Resource management
Every SWT component is mapped 1:1 to the relevant operating system. Therefore, every resource
that is created (that is, every time a constructor of a class is called) has to be released explicitly.

However, the following rule of thumb applies:
If a parent node is released, this also includes to the corresponding subnodes. It is sufficient to
release a window resource, for example. All control elements contained in it are then also released.

n LayoutManager
In AWT/Swing, the LayoutManager information is specified when elements are added to containers.
In SWT, the classes each have a so-called LayoutData object.
In the above example, a window with a container (display) is created.
Line 3: The container receives a GridLayout
Line 4: A button is created and added to the container
Lines 5-7: A GridData object is created and passed to the button. You can use it to pass
information, for example, the distance to the edge or distance within a line.

SAP AG JA200 4-9
SAP AG 2003
Special Features (2)
Standard dialogs
Numerous dialogs specific to the operating system
(ColorDialog, DirectoryDialog, FileDialog, FontDialog,
MessageBox, PrintDialog) can be used directly from SWT
...
1 Filedialog fd = new FileDialog( shell, SWT.OPEN );
2 fd.setFilterNames( new String[] {
3 TextFiles(*.txt),
4 All files(*.*)
5 }
6 );
7 fd.setFilterExtensions( new String[] {
8 *.txt,
9 *
10 }
11 );
12 String path = fd.open();
...



n Standard dialogs
ColorDialog (JColorChooser). Dialog for color selection.
DirectoryDialog (JFileChooser in DIRECTORIES_ONLY mode). Used for selection of
directories.
FileDialog (JFileChooser). For selection (saving or opening) of n files.
FontDialog (-). Used for installing an installed font.
MessageBox (JOptionPane). Used for displaying information, warnings, and so on.
PrintDialog (PrintJob.printDialog()). Dialog for selecting a printer or printer settings.

Line 1: This creates a standard dialog for opening files
Lines 2-6: To limit the files you can set filter names
Lines 7-11: To limit the files you can set filters (here, file endings)
Line 12: The dialog is displayed using open(). This is a modal dialog. Therefore, the processing
returns back to this point when the user has made his or her selection.


SAP AG JA200 4-10
SAP AG 2003
Example
A typical SWT application has the following structure:
1 public class MyShell {
2 protected Shell shell;
3 protected Display display;
4 public MyShell( String title ) {
5 this.display = new Display();
6 this.shell = new Shell( display );
7 }
8 void run() {
9 shell.open();
10 while (!shell.isDisposed()) {
11 if (!display.readAndDispatch())
12 display.sleep();
13 }
14 }
15 void stop() {
16 if (shell != null && !shell.isDisposed())
17 shell.dispose();
18 }
19 }
MyShell demo =
new MyShell( "SWT Demo );
demo.run();
demo.stop();



n Line 5: Create a display object
You use the display object to access the "desktop".
n Line 6: Create a shell object
This object is the main window of the application. It is typical for SWT applications that the parent
object is passed when new objects are created.
n Create the remaining widgets for the window
Create all the other widgets (for example, buttons, input fields, and so on) that you need for your
application.
n Line 9: Open the shell window
n Line 10: Run through a loop in which the operating system distributes messages to the shell
This loop is passed as long as the application is active. In the above example, each call of the
readAndDispatch() method transfers an event from the operating system to the display object, which
in turn passes these events on to the window or the control elements contained in it. If there is
nothing to do, the application is "sent to sleep" - until the next event.
n Line 17: Release the resources
Since SWT accesses operating system resources directly, it is very important that they are released at
the end.


SAP AG JA200 5-1
SAP AG 2003
Browser-Based GUI Development
l Applets
l Servlets
l Java Server Pages
l Preview: SAP Web Dynpro
Contents:




SAP AG JA200 5-2
SAP AG 2003
Course Overview Diagram
Introduction
Preface
AWT
Swing
Browser-Based GUI
Development
SWT




SAP AG JA200 5-3
SAP AG 2003
Unit Objectives
At the conclusion of this unit, you will be able to:
l Describe browser-based GUI development using
applets, servlets, or Java Server Pages




SAP AG JA200 5-4
SAP AG 2003
J2EE server
EJB
container
Web browser
Applet
container
Web container
Resource/enterprise data
Resource manager/
Enterprise Information System
Entity
bean
Session bean
Web component
(Servlet, JSP)
Java application
Client
Tier
Middle
tier
Back end
tier
Presentation
logic
Business
logic
Applet
JDBC
HTTP/HTML/XML
RMI
HTTP/XML
Java Components
Application components
l Web components
Servlets and Java Server
Pages (JSP)
Generate HTML pages and
XML data
Run within a Web
container
l Enterprise Java Beans (EJB)
Session beans and entity
beans
Encapsulate business
logic
Run within an EJB
container
l Applets
Run in applet containers
within a Web browser
l Standalone Java
applications



n Applications
Independent programs that can be started using the interpreter (Java VM).
n Applets
Applets are small programs that are stored (fully compiled) on a Web server together with the
HTML page descriptions of the Web sites. When a page is read, the browser downloads the applet
from the Web server and executes it locally.
n Beans
JavaBeans are components created in Java that can be used to easily reuse previously created
components in other projects. The JDK contains the package java.beans, which provides a number of
classes for working with JavaBeans.
n Servlets
In contrast to applets, servlets are not downloaded to the local computer but executed directly on a
server.
n Java Server Pages
JSP represents a cross-platform solution for the dynamic creation of Web sites. Within a Java Server
Page, dynamic contents are added using special JSP elements, while the formatting of the page is
described in HTML.

SAP AG JA200 5-5
SAP AG 2003
Java Server Pages Servlets Applets
Overview
1
2
3
SAP Web Dynpro
4




SAP AG JA200 5-6
SAP AG 2003
User interface designs not easy to
find (for example, you can only
add sounds in applets)
Program start: Interpreter
calls the main method
No need to use graphical interfaces ( text-
oriented input/output)
Class is executed at program
level using interpreter
Possible to access local
files and start programs
Application Versus Applet
Main
Application



n Applications
Applications are independent programs that need the (standalone) Java Interpreter for execution.
When a program is started, the Java Interpreter calls the main method of an application.

SAP AG JA200 5-7
SAP AG 2003
Always derived from
the applet class
Web browser instantiates
class (init and start)
No access to local files
Cannot start external
programs
Always event and
graphics-oriented
Additional possibilities
with regards to user
interfaces, for example sound
Program is executed in the Web browser, the applet
itself cannot run
Included in HTML
Application Versus Applet (2)
Applet
Applet
Hallo, ! am an applet
Applet started.



n Applets
Applets are included in HTML pages. They require a Web browser to be executed. The browser
loads the applet to its main memory via the Internet and then executes it.

Applets always work graphics-oriented and event-oriented.

SAP AG JA200 5-8
SAP AG 2003
Restrictions for Security Reasons
The "sandbox" security concept
Applet
The system allows the applet a limited and controlled area
(sandbox) in which to operate. All accesses outside this sandbox
are blocked by the security system.
In the user's file system, applets can neither read nor write
Applets can only communicate with the Internet server from which they
were downloaded
Applets cannot execute programs on the user's system
Applets cannot load programs on the local platform, including communally
used libraries, such as DLLs



n The security concept
Java applets can be downloaded from any page on the World Wide Web and executed on the client
system, which is why they are subject to the above restrictions for security reason (these can vary in
the different browser versions).

The Java security model makes it very difficult for hostile applets to damage the user's system.
However, problems can still arise: By entering the search term "hostile applets" you will find a
number of Java security articles on the WWW.

Any gaps in the security system are not down to the Java security concept, but it is the
implementation of the concept in different browsers that contains errors.

SAP AG JA200 5-9
SAP AG 2003
Restrictions in the Language Version
Choice of Java language version
With the support of the full Java language range, problems can
arise with different browsers/versions
(SecurityClassNotFoundException).
The usual procedure is:
Applets are written so that only features of Java 1.02 are
used, since these can run in all Java-enabled browsers
A JavaSoft add-on ("Java PlugIn") enables the use of the
language enhancement
The latest information and details about the subject
of "Java PlugIn" is available at the Web address
http://java.sun.com/products/plugin/index.html



n Restrictions of language version
It is possible that a browser cannot execute an applet if the applet uses any of the features of Java 1.1
or higher, because the browser does not support this language version (the only test environment that
fully supports these versions is JavaSoft's latest applet viewer).
This is a common source of errors for applet programmers. If you write a Java 1.3 applet and execute
it in a browser that does not support this language version, you will get security errors and "class not
found" errors. Additionally, other problems arise that will prevent the applet from being executed.

SAP AG JA200 5-10
SAP AG 2003
The Classes Applet, JApplet
java.applet
Every WWW applet must be derived from the class Applet
(JApplet)
The Applet class itself is a concrete graphics class in the above
class hierarchy
It is a rectangular screen element with (inherited) attributes:
General properties of Java objects (Object)
Visual element on the screen (Component)
Ability to take on other visual components (Container)
Ability to align the contained elements using so-called layouts (Panel)
java.awt java.lang
Object Component Container Panel Applet
javax.swing
JApplet



n Applet
The main program of an applet is always derived from the class java.applet.Applet. The Applet class
is derived from the basic classes Component and Container of the AWT (Abstract Windowing
Toolkit).
It is therefore a container, which can be integrated into an HTML page, for any graphical objects.

n Japplet
The JApplet class is a simple extension of java.applet.Applet. It is used for developing applets that
use Swing dialog elements for designing the interface.Otherwise, the differences between the two
classes are few.

SAP AG JA200 5-11
SAP AG 2003
Applet
public void init();
public void start();
public void stop();
public void destroy();
Initialization
public Applet();
Instantiation
Start of applet
End of applet
Destruction of applet
Browser
The communication between an applet and its browser runs in
various steps, in each of which the relevant methods are executed
Life Cycle of an Applet



n Loading
When an HTML page containing an applet is loaded, the browser's Java Interpreter loads the
specified class, creates an instance of it, and initializes it.
Constructor Applet() The default constructor should normally not be overloaded
Method init() The method is only executed once in the life cycle when the applet is loaded.
Here the applet is initialized.
n Start of applet
Then the browser starts the applet. The message "Applet running appears in the status bar. The
applet now "runs" until the HTML page is exited.
Method start() The method is executed as soon as the page is displayed
n Leaving the page
When the page is exited, the applet is stopped.
Method stop() The STOP method is executed when the applet has been stopped but not yet
removed from the memory (for example, change of page)
n Removing the applet
The browser decides when an applet is removed from the memory. In the case of a page change, it is
possible that the browser does not keep the applet in the memory, resulting in the methods
DESTROY and STOP being called (the methods INIT and START when returning to the page).
Method destroy() The method is called when the applet is removed from the memory.
This is always the case when the browser application is exited.

SAP AG JA200 5-12
SAP AG 2003
Applet
Applet
1 public void showStatus(String msg)
2 public String getAppletInfo()
3 public boolean isActive()
4 public void resize( . . . )
5 public URL getDocumentBase()
6 public URL getCodeBase()
7 public Image getImage( . . . )
8 public AudioClip getAudioClip( . . .)
9 public void play( . . . )
10 public void paint(Graphics g)
In the Applet class, the following methods are defined,
amongst others:
public void paint (Graphic GraphicObject) {
GraphicObject.drawString("Hello World,10,10);
}
//drawString(Output string, Position x, Position Y)



n Line 1: Writes a text in the status bar of the browser
Line 2: Specifications about the applet, the current version , and the author of the applet
Line 3: Checks whether the applet is active
Line 4: Changes the size of the applet (overloaded method of component)
Line 5: Returns the URL of the HTML page in which the applet appeared
Line 6: Returns the URL of the directory which contains the .class file of the applet
Line 7: Loads a graphic of the specified URL
Line 8: Loads a sound file of the specified URL
Line 9: Plays a sound file
n The paint() method
Line 10: Passes a graphics object that can be filled, for example, using the method drawString
(String, int, int)
The painting defines how an applet displays elements on the screen. This can be text, a line, colored
background, or a graphic. Painting can often take place during the life cycle of an applet. Use the
paint() method to enable an applet to paint on the screen.
n The Graphics class
Note that paint() receives an instance of the Graphics class as a parameter. It is created by the
browser and passed to paint. You must therefore ensure that the Graphics class is imported to the
applet code using the statement import java.awt.Graphics; at the start of the Java file.

SAP AG JA200 5-13
SAP AG 2003
Applets are included in an HTML document using the
<APPLET> </APPLET> tags
Between the tags, you can enter a text that is displayed for
browsers that do not support applets (an applet-enabled
browser ignores the text)
<APPLET CODE=MyFirstApplet WIDTH=300 HEIGHT=200>
Your browser does not support applets
</APPLET>
Including the Applet in the HTML Page
The <APPLET> tag



n Text between the tags
You should generally enter a text between the <APPLET></APPLET> tags, since it is possible that
older browsers do not support applets.

SAP AG JA200 5-14
SAP AG 2003
Including the Applet in the HTML Page (2)
Parameter of the APPLET tag
CODE String Specifies the name of the applet class
(including the ending .class)
WIDTH int Specifies the width of the screen
section reserved for the applet
HEIGHT int Specifies the height of the screen
section reserved for the applet
CODEBASE String Alternative path for class file
ARCHIVE String Specifies a .jar file that contains the Java
resources
NAME String Unique name of applet for communication
between several applets on an HTML page
VSPACE/HSPACE int Margin, upper/lower, left/right
. . .
o
p
t
i
o
n
a
l




SAP AG JA200 5-15
SAP AG 2003
For this purpose you can use the optional <PARAM> tag within
the <APPLET> </APPLET> tags
Each <PARAM> tag has the two parameters name and value,
which specify the name and value of the parameter
...
<APPLET CODE=MyApplet.class"
ALIGN="baseline
WIDTH="400 HEIGHT="100">
<PARAM NAME="PARAM_1"
VALUE=Hallo everyone">
<PARAM NAME="PARAM_2"
VALUE=123">
</APPLET>
...
Including the Applet in the HTML Page (3)
Parameter transfer to the applet
Hallo everyone
12J



n Passing parameters
The parameters are passed as a string. Therefore, there must be a conversion to the desired data type
in the applet.

When reading parameters, you should include an error routine, since not all parameters may have
been defined in the HTML code.

SAP AG JA200 5-16
SAP AG 2003
Within an applet, you can read the parameters using the
getParameter() method
1 import java.awt.*;
2 import java.applet.Applet;
3 public class MyApplet extends Applet {
4 String param1;
5 int param2;
6 public void init() {
7 param1= getParameter("PARAM_1");
8 param2= Integer.parseInt(getParameter("PARAM_2"));
9 }
10 public void paint(Graphics g) {
11 g.drawString(param1, 10, 10 );
12 g.drawString(Integer.toString(param2), 10, 30 );
13 }
14 }
Including the Applet in the HTML Page (4)




SAP AG JA200 5-17
SAP AG 2003
Java Server Pages Servlets Applets
Overview 10
1
2
3
SAP Web Dynpro
4




SAP AG JA200 5-18
SAP AG 2003
Overview
Servlets and applets are conceptually similar
Applets are loaded and started by the Web browser
The browser serves as a container for applets
Web server
Servlets are loaded and started by the servlet engine of a
Web server or application server
Servlet
engine
Browser



n Browser as a container for applets
Applets are loaded by the Web browser and started there locally. The browser adopts the function of
a container for the applets and provides an infrastructure like the virtual machine or network
attributes. Within a Java environment in the browser, multiple applets can be included in parallel.
n Servlet engine as a container for servlets
For servlets the situation is similar. Here a container is also required that manages all the servlets. It
can either be embedded in a Web server or in an application server. Unlike applets, servlets are
always executed on the Web server. The servlet can import parameters and form contents via an
input channel and, in the output stream, generates an HTML page, which the container passes to the
client.

SAP AG JA200 5-19
SAP AG 2003
Web
server
Browser
Servlet
engine
Virtual machine
javax.servlet.Servlet
Request Response
Servlet
response
Servlet
request
javax.servlet.http.
HttpServlet
javax.servlet.
GenericServlet
MyHttpServlet
MyGenericServlet
MyHttpServlet
MyHttpServlet
MyGenericServlet
MyGenericServlet
Web Server and Servlet Engine



n Web server and servlet engine
The browser sends a request to the Web server. With the help of a special tag Of the used URL
(Uniform Resource Locator), the web server recognizes that it is dealing with the call of a servlet and
passes the request on to the Servlet engine.
A typical servlet request is structured as follows:
"protocol://server:port/servlettag/servletname"
For example, http://www.sap.com/servlet/OurFabulousServlet
The servlet engine creates a new servlet instance and calls the relevant methods ("servlet container").
In contrast to applets, the Java codes is executed on the Web server. If several requests concern the
same servlet, the servlet engine starts several threads.

The servlet engine uses the interface javax.servlet.Servlet to communicate with a servlet. Therefore,
every servlet must either implement this interface or be derived from a class that implements it (for
example, javax.servlet.GenericServlet or javax.servlet.http.HttpServlet).

SAP AG JA200 5-20
SAP AG 2003
A server is servlet-enabled if it meets the Java servlet and
Java Server Pages (JSP) specifications
The servlet component can be an integral
part of the server or an addition to be
installed later
The SAP Web Application Server
integrates Internet standard
technology into the technological basis
of the R/3 System.
The first step is to install a servlet-enabled Web server
Developing Servlets



n Servlet-enabled Web server
To be able to develop and test servlets (and Java Server Pages), you require a servlet-enabled Web
server. The Apache Group's Tomcat is the official reference implementation. For testing servlets and
JSP, Tomcat can be used either as a standalone application or as an addition to the Apache server.
Like Apache, Tomcat is free.
n SAP Web Application Server
With the Web Application Server, SAP also provides a servlet-enabled Web server that allows you
to program Web applications using ABAP (BSP) or Java (servlets/JSP).

SAP AG JA200 5-21
SAP AG 2003
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletHelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY><B>Hello World!</B></BODY>");
out.println("</HTML>");
out.close();
}
}
A servlet must either implement the Servlet interface or be
derived from a class that implements it
Using the methods defined in it, the servlet communicates with
the servlet container
Developing Servlets (2)



n Developing and deploying servlets
As soon as the Web server recognizes that the incoming request is a servlet, it passed the request on
to the servlet container. The servlet container in turn manages all the servlets, addresses the servlet
that the user wants to use, and passes data streams for input and output.
The servlet reads parameters and form contents via an input channel and, in the output stream,
generates an HTML page, which the container passes on to the client.

SAP AG JA200 5-22
SAP AG 2003
Virtual machine
The third step is to install the servlet on the Web server
("deploying")
Web server
MyServletHelloWorld
Servlet
engine
Developing Servlets (3)



n Developing and deploying servlets
After developing your new servlet class, you must install the executable code (.class file) on your
Web server ("deploying"). The procedure depends on what Web server you are using. After
successful installation, you can start your servlet by calling a browser

The topic of "Developing Web applications using Java" is covered in more detail in the SAP Java
course "JA300: InternetKit".

SAP AG JA200 5-23
SAP AG 2003
Java Server Pages Servlets Applets
1
2
3
SAP Web Dynpro
4
Overview 11




SAP AG JA200 5-24
SAP AG 2003
Servlets are server programs that create Web pages dynamically
In a Java program (the servlet), HTML statements are used that
are sent to the output stream using println() or similar
Java Server Pages (JSP) are server programs that also create
Web pages dynamically
Java code is used in an HTML page
Java Server Pages



n Disadvantages of servlets
When developing servlets, the following problems arise:
It is difficult to separate the content (model) and the visualization (view). As soon as the
appearance changes, the program has to be restructured.
Generally, the programmer and the designer are not the same person, and the latter not only
usually has limited Java knowledge but would also like to create Web pages using special
programs, such as Dreamweaver or Frontpage, and not work with a Java IDE.

n JSP (Java Server Pages)
For this reason JSPs were developed. These are HTML files in which Java code is used.

SAP AG JA200 5-25
SAP AG 2003
Can be edited by standard HTML editors
Can include Java code
Should include too many Java scriptings
Work closely together with Java Beans
Contain implicit Java objects
Can contain special tags that are specified in the JSP
specification
Can use their own tag libraries
Can be linked with servlets and other resources
JSPs:
Java Server Pages (2)




SAP AG JA200 5-26
SAP AG 2003
1 <HTML>
2 <HEAD> <TITLE> HelloWorld </TITLE> </HEAD>
5 <BODY>
6 Hello world. It is today <% out.print( new java.util.Date() ); %>
7 </BODY>
. . .
8 public class _0002fjsp_0002fHelloWorld_0002ejspHelloWorld_jsp_0
9 extends HttpJspBase {
. . .
10 public void _jspService(HttpServletRequest request,
11 HttpServletResponse response)
12 throws IOException, ServletException {
. . .
13 out = pageContext.getOut();
14 out.write("<HTML>\r\n<HEAD>\r\n<TITLE> HelloWorld);
15 out.write("</TITLE>\r\n</HEAD>\r\n<BODY>\r\nHallo Welt.);
16 out.write("It is today ");
17 out.print( new java.util.Date() );
18 out.write("\r\n</BODY>");
. . .
JSP engine
Java Server Pages (3)



n Automatic generation of servlets
Once a JSP page has been installed on the Web server, it can be called using a URL. When it is first
called, the JSP engine of the Web server creates and compiles a servlet from the JSP page in the
background and also installs it on the Web server. This call and any additional calls are now
processed using the servlet.

The servlet is generated automatically by the Web server. This is not visible to the user or the
developer of the JSP page.

The topic of "Developing Web applications using Java" is covered in more detail in the SAP Java
course "JA300: InternetKit".

SAP AG JA200 5-27
SAP AG 2003
Java Server Pages Servlets Applets
Overview 12
1
2
3
SAP Web Dynpro
4




SAP AG JA200 5-28
SAP AG 2003
SAP Web Dynpro
The Web Dynpro technology consists of a development
environment as well as a runtime environment
G
e
n
e
r
a
t
o
r R
R
Gen. of
runtime
objects
XML, Java
source code,
...
D
e
p
l
o
y
m
e
n
t
W
e
b
D
y
n
p
r
o
r
u
n
t
i
m
e
Application-
specific
objects
Web Dynpro Tools
(Eclipse)
Metadata API
Local XML files
R
Project
Browser
Application
Modeler
View
Designer
Controller
/ Context
Editor
Model
Editor
Design time Runtime




SAP AG JA200 5-29
SAP AG 2003
The Web Dynpro development tools are based on the Eclipse
platform
WYSIWYG View Designer
SAP Web Dynpro (2)
Application Modeler



n SAP Web Dynpro
The SAP Web Application Server 6.30 sees the introduction of a new type of development of
browser-based GUIs: SAP Web-Dynpro.
This is a development environment, (initially) based on the Eclipse platform, and a runtime
environment.

The topic of "Developing Web applications using SAP Web Dynpro" is covered in more detail in the
SAP Java course "JA300: InternetKit".

SAP AG JA200 5-30
Exercises


Unit: Browser-Based GUI Development
Topic: Applets

At the conclusion of this exercise, you will be able to:
Program a simple applet
Help:
Start JViewer. In the directory tree, choose the node Exercises +
lab04 + 1. Take a look at the graphic(s).
JVIEWER

4-1 Create the applet class MyApplet.

Open the package com.sap.epf.ja200.exc.lab04.
Define the class MyApplet. The class is to be public and belong to the package
com.sap.epf.ja200.exc.lab04.

Import the following classes/packages.
import java.applet.*;
import java.awt.*
import java.awt.event.*;
Derive your class or implement the following interfaces.
implements Applet
The applet is to:
1. Import the message parameter from the HTML page
2. Provide a button. When the user presses this button, the imported
parameter should be displayed in different font sizes.
For this purpose, overwrite the paint() method and implement the
following loop.
for (int i=9; i<30; i+=5, y+=i) {
Font font = new Font("Dialog", Font.BOLD, i);
g.setFont(font);
g.drawString(output, 5, y);
}
4-2 Insert the applet in an HTML page.



SAP AG JA200 5-31
Solutions


Unit: Browser-Based GUI Development
Topic: Applets

4-1 Create the applet class MyApplet.

package com.sap.epf.ja200.sol.lab04;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class MyApplet extends Applet
implements ActionListener {
private String output, msg;
public void init() {
super.init();
msg = getParameter("message");
Button button = new Button("Press me");
this.add(button);
button.addActionListener(this);
}

public void actionPerformed( ActionEvent event ) {
output = "Your message: " + msg;
System.out.println("Button pressed");
repaint();
}

public void paint(Graphics g) {
super.paint(g);
int y = 30;
for (int i=9; i<30; i+=5, y+=i) {
Font font = new Font("Dialog", Font.BOLD, i);
g.setFont(font);
g.drawString(output, 5, y);

SAP AG JA200 5-32
}
}

public java.lang.String[][] getParameterInfo() {
String[][] info = {
{"message", "String", "Message"},
};
return info;
}
}
4-2 Insert the applet in an HTML page.

<HTML>
<HEAD>
<TITLE>MyApplet</TITLE>
</HEAD>
<BODY>
<H1>MyApplet</H1>
<A
HREF=..\src\com\sap\epf\ja200\sol\lab04\MyApplet.java>
Source code for MyApplet
</A>
<p>
<APPLET
CODE=com.sap.epf.ja200.sol.lab04.MyApplet.class
WIDTH=550 HEIGHT=300>
<PARAM NAME=message VALUE="Applets are cool !">
</APPLET>
</BODY>
</HTML>




SAP AG JA200 6-1
Appendix
Class com.sap.epf.ja100.util.IconFactory
This class provides the icons used in the GUIs.
The internal class MultiIcon provides two icons for the states selected/not selected.

package com.sap.epf.ja100.util;

import java.util.Hashtable;
import javax.swing.*;
import java.awt.*;
import java.net.URL;

public final class IconFactory {
private static Hashtable iconPool = new Hashtable();

public IconFactory() {
iconPool.put( "Delete",
new MultiIcon( "DeleteI.gif","DeleteS.gif" ) );
iconPool.put( "Add",
new MultiIcon( "AddI.gif", "AddS.gif" ) );
iconPool.put( "Edit",
new MultiIcon( "EditI.gif", "EditS.gif" ) );
iconPool.put( "Save",
new MultiIcon( "SaveI.gif", "SaveS.gif" ) );
iconPool.put( "ScrJA100",
new MultiIcon( "JA100.gif", null ) );
iconPool.put( "ScrJA200",
new MultiIcon( "JA200.gif", null ) );
. . .
}


/**
* Returns MultIcon for specified key access
*/
public static MultiIcon getIcon( String _key )
throws NullPointerException {
MultiIcon icon = (MultiIcon)iconPool.get( _key );
if( icon == null ) throw new NullPointerException();
return icon;
}


SAP AG JA200 6-2

/**
* Inner class MultiIcon, Immutable Pattern
* Usage:
* IconFactory.MultiIcon multiIcon =
* IconFactory.getIcon( ... );
* JLabel label = new JLabel();
* label.setIcon( multiIcon.getInitial() );
*/
public class MultiIcon extends ImageIcon {

ImageIcon iconInitial = null;
ImageIcon iconSelected = null;

public MultiIcon( String initial,
String selected ) {
try {
Dummy dummyInit = new Dummy();
Dummy dummySel = new Dummy();
iconInitial = new ImageIcon(
dummyInit.loadImage(
"images/"+initial ) );
if ( selected != null ) {
iconSelected = new ImageIcon(
dummySel.loadImage(
"images/"+selected ) );
} else {
iconSelected = new ImageIcon(
dummySel.loadImage(
"images/"+initial ) );
}
} catch ( Exception exc ) {
exc.printStackTrace();
}
}

public ImageIcon getInitial() {
return iconInitial;
}

public ImageIcon getSelected() {
return iconSelected;

SAP AG JA200 6-3
}

public ImageIcon getInitialScaled( int width,
int height ) {
Image img = iconInitial.getImage();
return new ImageIcon(
img.getScaledInstance(
width,height,Image.SCALE_SMOOTH)
);
}

public ImageIcon getSelectedScaled( int width,
int height ) {
Image img = iconSelected.getImage();
return new ImageIcon(
img.getScaledInstance(
width,height,Image.SCALE_SMOOTH)
);
}
}



public class Dummy
extends java.beans.SimpleBeanInfo {
public Dummy() {
super();
}
}
}



Class com.sap.epf.ja100.persist.PersistManager
This class is responsible for the creation of objects from persistent data sources.

Method initializeConnectors:
For every data source there is a connector class, that is instantiated at this point.

Method initializeFactories:
For every model class there is a factory. This factory is assigned the relevant connector references and creates the
corresponding model objects from the persistent data.
The model objects are stored in data containers and can then be read using the PersistManager.


package com.sap.epf.ja100.persist;

import com.sap.epf.ja100.app.*;

SAP AG JA200 6-4
import com.sap.epf.ja100.model.*;
import com.sap.epf.ja100.persist.*;
import com.sap.epf.ja100.util.*;
import java.io.*;
import java.util.*;

public class PersistManager implements IManager {
private static PersistManager persistManager = null;
private Hashtable factoryCollection;
private Hashtable poolCollection;
private IPool addressPool;
private IConnector addressConReader = null;
private IConnector addressConWriter = null;
. . .

private PersistManager( StartScreen startScreen ) {
registerManager();
. . .
initializeConnectors();
initializeFactories();
}


private void initializeConnectors() {
Class readerClass = null;
Class writerClass = null;
try {
readerClass = Class.forName(
StaticData.getProperty( "addressReader" ) );
writerClass = Class.forName(
StaticData.getProperty( "addressWriter" ) );
. . .
} catch (ClassNotFoundException exc) {
logger.log(Logger.LOGLEVEL_SEVERE, exc);
} catch (ClassCastException exc) {
logger.log(Logger.LOGLEVEL_SEVERE, exc);
} catch (InstantiationException exc) {
logger.log(Logger.LOGLEVEL_SEVERE, exc);
} catch (IllegalAccessException exc) {
logger.log(Logger.LOGLEVEL_SEVERE, exc);

SAP AG JA200 6-5
}

try {
addressConReader.setUrl(
StaticData.getProperty("addressReaderPath"));
addressConWriter.setUrl(
StaticData.getProperty("addressWriterPath") );
. . .
} catch (NullPointerException exc) {
logger.log( Logger.LOGLEVEL_SEVERE, exc );
}
}


private void initializeFactories() {
factoryCollection = new Hashtable();
factoryCollection.put( "Address",
AddressFactory.getInstance(
addressConReader, addressConWriter)
);
. . .
}

public IFactoryFacade getFactory( String key )
throws Exception {
IFactoryFacade iFF =
(IFactoryFacade)factoryCollection.get( key );
if (iFF == null) throw new NullPointerException();
return iFF;
}

public void loadBusObjects() {
poolCollection = new Hashtable();

addressPool = BusObjectPool_L.getInstance(
"Address" );

poolCollection.put( "address", addressPool );

. . .
}

public IPool getBusObjectPool( String key )
throws NullPointerException {

SAP AG JA200 6-6
IPool busObjPool = (IPool)poolCollection.get(key);
if (busObjPool == null)
throw new NullPointerException();
return busObjPool;
}

public void registerManager() {
StaticData.registerManager( "persist", this );
}
. . .
}

You might also like