Section 508 for Software Development Coding Examples

Java

Provision A

§1194.21(a) “When software is designed to run on a system that has a keyboard, product functions shall be executable from a keyboard where the function itself or the result of performing a function can be discerned textually.”

Set Mnemonics on Components
Setting mnemonics on application components gives disabled users a quick way to change focus via the keyboard. Mnemonics are keyboard equivalents for component activation, such as Alt+E for Edit on a menubar. Class libraries, like the Java Foundation Classes (JFC), should provide for keyboard mnemonics in their design.

To set a mnemonic for a component such as JButton, pass a Java virtual key as defined in java.awt.KeyEvent to the setMnemonic method. For example, to set the mnemonic to Alt+G use:

JButton myButton = new JButton();
myButton.setMnemonic(java.awt.event.KeyEvent.VK_G);

For components that do not have a setMnemonic method, the JLabel component may be used to change focus. In JFC, the JLabel component has a setDisplayedMnemonic method, which changes the focus to the component it is labeling, as defined in the setLabelFor method. For example:

//Create a JLabel
JLabel myLabel = new JLabel("File Name");

//Create a JTextArea
JTextArea myTextArea = new JTextArea("MyFilename");

//Associate label with text area
myLabel.setLabelFor(myTextArea);

//Set ALT+G for the text area
myLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_G);

Some components should be accessible via standard keyboard mappings, such as those in the logical tabbing order. For these components, a mnemonic does not need to be set to give them focus. However, these components should be accessible using the keyboard, such as through tabbing, arrow keys, or customized keyboard action.

Use Accelerators for Commonly Used Functions

Accelerators are keyboard shortcuts for actions that are frequently performed (such as Ctrl+P for Print or Ctrl+S for Save). Class libraries, like the Java Foundation Classes, should provide for accelerators in their design. For example, JFC JmenuItem components provide a setAccelerator method to allow the developer to set a keyboard accelerator key. This allows the user to activate a menu item without navigating the menu hierarchy.

Let's take a look at adding the accelerator Alt+M to a menu item in JFC. To assign the Alt+M accelerator to a menu item, use the Swing KeyStroke class to create the keystroke, and pass it to the JMenuItem setAccelerator method as shown in this code:

//Create Menu Item
JMenuItem myMenuItem = new JMenuItem();

//Set Accelerator for Menu Item
myMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.ALT_MASK));

Provide a Logical Keyboard Tabbing Order
Provide a logical navigation sequence between interface objects such as buttons, lists and user input fields. Navigation is accomplished by tabbing between components or groups and by using the arrow keys within a component group or component's elements. The order in which the user Tabs among components or groups of components and the order in which the user uses the arrow keys to navigate within a group of components should make sense.

A component is inclusive in the tabbing order when added to a panel and if its isFocusTraversable() method returns true. A component can be removed from the tabbing order by simply extending the component, overloading this method, and returning false.

Excessive use of tabbing can reduce the usability of software for both disabled and non-disabled users. Some components may use a keyboard alternative (mnemonics and accelerators) instead of being part of the tabbing order.

Be Aware of Reserved Keyboard Mappings for Mobility Access Features and the Operating System
The keyboard bindings selected for use in the application should not conflict with the system keyboard mappings or the reserved mobility access keyboard modifiers of the operating system on which the application will run.

These keys are reserved for assistive technologies that assist users with disabilities:

Provision B

§1194.21(b) “Applications shall not disrupt or disable activated features of other products that are identified as accessibility features, where those features are developed and documented according to industry standards. Applications also shall not disrupt or disable activated features of any operating system that are identified as accessibility features where the application programming interface for those accessibility features has been documented by the manufacturer of the operating system and is available to the product developer.”

Be Aware of Reserved Keyboard Mappings for Mobility Access Features
The keyboard bindings selected for use in your application should not conflict with the system keyboard mappings or the mobility access modifiers of the operating systems on which your application will run.

Several keys exist for use with assistive technologies that are designed to assist users with motor disabilities. They are:

Java Access Bridge
The Java Access Bridge makes it possible for Microsoft Windows-based assistive technology, such as Microsoft Windows-based screen readers, to access and interact with the Java Accessibility API. The Access Bridge is a class where part of the class code is supplied by a dynamically linked library (DLL) on the Windows system. The assistive technology running on the host platform communicates with the Windows-native DLL portion of the bridge class. The native code of the bridge class communicates through the JVM with the Java Accessibility utility support and the Java Accessibility API on the individual user interface objects of the Java-based application. The Java Accessibility API is implemented in Java Foundation Classes Swing user-interface components. However, developers writing custom components must specifically implement the Java Accessibility API in those components. Let's take a look at an example of code that results in a custom component that implements the Accessibility API:

// Accessible custom component using JFC JComponent as a base
class MyComponent extends JComponent implements Accessible {

public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new MyAccessibleComponent();
}
return accessibleContext;
}

protected class MyAccessibleComponent extends AccessibleJComponent {
// Inherit everything, override nothing
}

…
}

Provision C

§1194.21(c) “A well-defined on-screen indication of the current focus shall be provided that moves among interactive interface elements as the input focus changes. The focus shall be programmatically exposed so that assistive technology can track focus and focus changes.”

There are several ways to request the focus in the Java Foundation Classes (JFC). The provision method occurs when focus is requested automatically in JFC through keyboard access of a component. In this case, the component executes the java.awt.requestFocus method. A default focus may also be set using one of the two techniques described below. Note that the second technique only applies if the default focus will be set to a JButton.

Using the Window Activation Trigger to Set the Focus in JFC
This code illustrates how to set the focus in JFC by using the Window activation trigger:

JFrame jFrame = new JFrame();                  		// Create a Frame
JTextField myTextField = new JTextField(); 		// Create a JTextField Component

// Add the text field to the root pane
jFrame.getRootPane().add(myTextField);

// Add a Window listener to the JFrame that requests the text field to have focus
// when the window is activated
jFrame.addWindowListener(new java.awt.event.WindowListener() {

void windowActive() {
myTextField.requestFocus();  	// Do this if focus has never been set
// before in your window.
// Swing remembers the last focus set.
}
……
});
jFrame.show();  // Show the window

Using the javax.swing.JRootPane SetDefaultButton Method

1JFrame jFrame = new JFrame();                  		// Create a frame
JButton myButton = new  JButton();  				// Create a JTextField Component

jFrame.getRootPane().add(myButton);         			// Add the text field to the root pane
jFrame.getRootPane().setDefaultButton(myButton);		// Give the button the default focus
jFrame.show(); 					       	// Show the window

1IBM Guidelines for Writing Accessibility Applications Using 100% Pure Java – Online: available at: http://www-3.ibm.com/able/snsjavag.html

Provision D

§1194.21(d) “Sufficient information about a user interface element including the identity, operation and state of the element shall be available to assistive technology. When an image represents a program element, the information conveyed by the image must also be available in text.”

Label Components Using Swing's JLabel Component
When using the JFC/Swing components, objects containing non-editable text will have their accessible names set automatically with the label value. However, some objects contain no static text and must have their accessible names set programmatically. For an object such as a text field, label the object with an instance of JLabel. Then, use the setLabelFor() method to associate the label and the text field.

In this example code, the text field component will get the AccessibleName and AccessibleDescription of the label.

JTextField myTextField = new JTextField(10);
Label myLabel = new Label("Phone Number");
myLabel.setLabelFor(myTextField);
myLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_P));

In addition, the label also has a mnemonic. Therefore the label requests focus to the text field component specified by the labelFor property when the mnemonic is activated.

Use AccessibleRelation to Associate a JLabel With Another Component
In Java 1.3, you must define an AccessibleRelation of AccessibleRelation.LABEL_FOR to define a label for a specific component. Then add an AccessibleRelation.LABELED_BY for the target component. This example, a screen reader should speak "First Name:" followed by the text entry field role and text, in the entry field (if any), whenever the user tabs to the entry field.1

//Create a label of First Name: The AccessibleName will assume
//this initial setting in JFC
JLabel myLabel = new JLabel("First Name:");

//Create an empty text field
JTextField myTextField = new JTextField();

//Create a LABEL_FOR relationship in the JLabel that indicates that the
//label is a label for the text field.
AccessibleRelationSet arSet1
     = myLabel.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelation ar1
     = new AccessibleRelation(AccessibleRelation.LABEL_FOR, myTextField);
arSet1.add(ar1);


//Create a LABEL_BY relationship in the JTextField that
//indicates that the text field is labeled by the label of First Name.
AccessibleRelationSet arSet2
      = myLabel.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelation ar2
      = new AccessibleRelation(AccessibleRelation.LABELED_BY, myLabel);
arSet2.add(ar2);

//Add the components to your application.

1 IBM Guidelines for Writing Accessibility Applications Using 100% Pure Java – Online: available at: http://www-3.ibm.com/able/snsjavag.html.

Name Logical Groups
When GUI components have a logical association, group those components together and assign them a name. One way to group a set of components is to add the group to a JPanel and then set the JPanel's AccessibleName property. A simpler method is to use a JPanel with a JFC TitledBorder. In this case, the accessible name is set automatically.

In Java 1.3, an accessible relation was created to define objects, which are a member of a given group. This code indicates how you can take an arbitrary component set that implements the Accessibility API and create a named group containing accessible components indicating the relationship to the enclosing group2:

//Create a named group panel with name "Size Options"
JPanel groupPanel = new JPanel();
groupPanel.getAccessibleContext().setAccessibleName("Size Options");

//Create a radio button and indicate it as being a member of the group
JRadioButton radioButton1 = new JRadioButton("Small");
AccessibleRelationSet  arSet
      = radioButton1.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelation ar
      = new AccessibleRelation(AccessibleRelation.MEMBER_OF, groupPanel);
arSet.add(ar);

//Create a radio button and indicate it as being a member of the group
JRadioButton radioButton2 = new JRadioButton("Medium");
AccessibleRelationSet  arSet
      = radioButton2.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelation ar
      = new AccessibleRelation(AccessibleRelation.MEMBER_OF, groupPanel);
arSet.add(ar);

//Create a radio button and indicate it as being a member of the group
JRadioButton radioButton3 = new JRadioButton("Large");
AccessibleRelationSet arSet
      = radioButton3.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelation ar
      = new AccessibleRelation(AccessibleRelation.MEMBER_OF, groupPanel);
arSet.add(ar);

//Add the components to the panel
groupPanel.add(radioButton1);
groupPanel.add(radioButton2);
groupPanel.add(radioButton3);

2 IBM Guidelines for Writing Accessibility Applications Using 100% Pure Java – Online available at: http://www-3.ibm.com/able/snsjavag.html.

Implement the Accessible Interface
All objects should implement the Accessible interface. This interface provides the standard mechanism for an assistive technology to get descriptive information. First, obtain the AccessibleContext by calling AccessibleContext.getAccessibleContext() method. Then, set the AccessibleName and AccessibleDescription. For JFC/Swing components, it is not necessary to explicitly set an accessible name because this is set automatically. For example, the default accessible name for the JButton class is the JButton label.

Let's take a look at code that uses a JFC/Swing component:

JButton myButton = new JButton("My Button");
myButton.getAccessibleContext().setAccessibleName("My Button");  // Not needed
myButton.getAccessibleContext().setAccessibleDescription("Click this button to see me.");

This code can be used to retrieve the accessible name and description:

String buttonName =  myButton.getAccessibleContext().getAccessibleName();
String buttonDescription =  myButton.getAccessibleContext().getAccessibleDescription();

Using custom components, the object must implement Accessible. In addition, the accessible role must be explicitly set as shown in this sample code:3

//Custom component WarningLight
public class WarningLight extends JComponent implements Accessible {

public AccessibleContext getAccessibleContext() {
// variable accessibleContext is protected in superclass
if (accessibleContext == null) {
accessibleContext = new AccessibleWarningLight();
}
return accessibleContext;
}

protected class AccessibleWarningLight extends AccessibleJComponent {
public AccessibleRole getAccessibleRole() {
return AccessibleRole.ALERT;
}
}

// Implementation of WarningLight omitted...
}

…..

WarningLight warningLight = new WarningLight;
warningLight.getAccessibleContext().setAccessibleName("Warning Light");
warningLight.getAccessibleContext().setAccessibleDescription("Warning Light turns red when
activated.");

This code is an example of how to retrieve the accessible name, description, and role:

String warningLightName =  warningLight.getAccessibleContext().getAccessibleName();
String warningLightDescription =
warningLight.getAccessibleContext().getAccessibleDescription();
String warningLightRole
warningLight.getAccessibleContext().getAccessibleRole().setDisplayString();

Use AccessibleState to describe a particular state of a component. The actual state of a component is defined as an AccessibleStateSet, which is a collection of an object's AccessibleStates.

AccessibleStateSet maintains a collection of the AccessibleState settings for a given object that implements Accessible. It has methods to add and remove AccessibleStates to its collection. An assistive technology would query the current AccessibleStateSet to determine the state of an object. The set of state information for each Accessible object should be maintained. Examples of state information are "checked" for a checkbox, or "vertical" for a scroll bar. To modify the state set, check to see if the AccessibleStateSet contains the AccessibleState, then add or remove the AccessibleState.

Whenever a state is added to or removed from the AccessibleStateSet, an ACCESSIBLE_STATE_PROPERTY change event must be fired in AccessibleContext. This allows assistive technology to be notified when specific properties change.

3 Code example taken from Developing Accessible JFC Applications available at: http://www.sun.com/access/developers/developing-accessible-apps/.

Implement the Accessible Interface on Objects That Have an Associated Icon
The Accessible interface should be implemented by any object, which has an associated icon (e.g., buttons). This interface provides the standard mechanism for an assistive technology to get descriptive information about icons. Applications can determine if an object supports the Accessible interface by first obtaining its AccessibleContext and then calling the AccessibleContext.getAccessibleContext() method. If the return value is not null, the object supports this interface.

The accessibleDescription property of this object is a short localized phrase describing the purpose of the object. For example, as this code shows, in the case of a "Submit" button the accessibleDescription could be "Submit information and place order":

JButton submitButton = new JButton("Submit");
submitButton.getAccessibleContext().setAccessibleDescription (“Submit information and place
	order”);

Implement Accessible Interface if Object Only Has an Icon
If the object only has an icon, implement the Accessible Interface and set the AccessibleName on it as a text alternative. If set, the ToolTips text serves as the accessible name for a component. However, if the ToolTips text is being used for something else, set the component's accessible name. Here's an example:

JButton button = new JButton(new ImageIcon("image.gif"));
button.setToolTipText("Button Name");

// If tool tip is being used for something else, set the accessible name.
button.getAccessibleContext().setAccessibleName("Button Name");

Implement AccessibleIcon on Object
If using Java SDK 1.3 or later, the AccessibIe Icon interface extends accessibility to icons. It provides a method to set an accessible description and to retrieve the description as well as the icon height and width. In the following example, the protected inner class ImageIcon.AccessibleImageIcon implements AccessibleIcon:

JButton button = new JButton(new ImageIcon("image.gif"));
button.getAccessibleContext().setAccessibleName("Button Name");

Use the ImageIcon with Description
To retrieve the accessible information about the icon, use the ImageIcon with description. Some JFC/Swing components, such as JLabel and JButton, can be decorated with an icon. Swing provides a particularly useful implementation of the Icon interface: ImageIcon, which paints an icon from a GIF or JPEG image. This code4 shows three labels: the first label contains the icon and text, the second label contains only text, and the third label contains only the icon.

ImageIcon myIcon = new ImageIcon("images/image.gif", "a yellow blob");
JLabel label1 = new JLabel("Image and Text", myhIcon, JLabel.CENTER);
JLabel label2 = new JLabel(“Text-Only Label”);
JLabel label3 = new JLabel(myIconcon);

The first argument to the ImageIcon constructor specifies the file to load, relative to the directory containing the application's class file. The second argument provides a description of the icon, to be used by assistive technologies.

4 Code example taken from Java 2 Platform Std. Ed. v1.3.1 Online Documentation available at: http://java.sun.com/j2se/1.3/docs/api/.

Provision E

§1194.21(e) “When bitmap images are used to identify controls, status indicators, or other programmatic elements, the meaning assigned to those images shall be consistent throughout an application's performance.”

To ensure that any image utilized in an application has a consistent meaning, the image should be used for only one function or purpose throughout the application.

For example, a print feature and accompanying bitmap image may be used several times in many applications. Therefore, the print bitmap image should only be used to signify the print function.

Provision F

§1194.21(f) “Textual information shall be provided through operating system functions for displaying text. The minimum information that shall be made available is text content, text input caret location, and text attributes.”

All classes that present textual information on the display (including editable text) should implement the AccessibleText interface. This interface provides the standard mechanism for an assistive technology to access that text via its content, attributes, and spatial location. This example shows how to retrieve the text information from an object (myComponent) that implements Accessible and AccessibleText:

AccessibleContext accessContext = myComponent.getAccessibleContext();
AccessibleText accessText = accessContext.getAccessibleText();

// Get Caret Location
int caretLocation = accessText.getCaretPosition();

// Get Selected Text
String selectedText = accessText.getSelectedText();

// Get Text Attributes
AttributeSet attest = accessText.getCharacterAttribute(index);
// Foreground color
Color foregroundColor = (Color) accessText.getAttribute(StyleConstants.Foreground);
// Background color
Color backgroundColor = (Color) accessText.getAttribute(SytleConstants.Background);

Provision G

§1194.21(g) “Applications shall not override user selected contrast and color selections and other individual display attributes.”

Java provides you with the ability to ensure the integrity of these user-defined settings:

Contrast
If you use Windows Pluggable Look and Feel (PLAF) with Java Foundation Class (JFC) and JFC-standard components, your application will automatically inherit the operating system's color settings for high contrast. Note, however, that the inheritance of color settings will only take place when the application is operated on a Windows system that has graphical user interface (GUI) components.

To use high contrast settings with JFC on other platforms, a PLAF that uses Java Native Interface (JNI) to access a Dynamic Link Library (DLL) will need to be created. This DLL will access system font and color settings for each component. Although not required, it is helpful if the application responds to changes in these settings (in order to avoid having to stop and restart the application).

If the application uses custom components that do not support JFC or PLAF, the method described above should also be used to access the appropriate systems settings. If the application runs only on Windows systems, then you may wish to create this new PLAF from the Windows PLAF.

For components that do not have corresponding standard system controls, high contrast capabilities will need to be added to the components that respond to system changes in the setting of high contrast features.

Windows System Specifics
Choose only those colors that can be user-customized through use of the Accessibility Settings feature for high contrast (located in the Control Panel). Access to this information (from Windows) is through Call GetSysColors.

Windows software can check for the high contrast setting by calling the SystemParametersInfo function with the SPI_GETHIGHCONTRAST value. Applications should query and support this value during initialization and when processing WM_COLORCHANGE messages.

Font and Colors Settings
Windows Systems
The application will automatically inherit system color settings, for high contrast, on all Windows systems for standard GUI components if you use Windows' Pluggable Look and Feel (PLAF) (provided with JFC) and the standard JFC components. Note that the Windows PLAF does not pick up system font settings. In order to meet the font requirement for Windows, the technique described below may be used.

Other Operating Systems
In order to use system font and color settings with JFC on other platforms, a PLAF that uses Java Native Interface (JNI) to access a Dynamic Link Library (DLL) will need to be created. Although not required, it is helpful if your application responds to changes in system font and color (in order to avoid having to stop and restart your application). If the application will only run on Windows systems, then you may wish to create this new PLAF from the Windows PLAF.

If you have a custom component that does not support JFC or PLAF you will need to access the appropriate systems settings using JNI and a DLL (as described above).

Custom Colors and Fonts
Some applications may require, or benefit from, the use of specialized colors or fonts. In these cases, the values should be stored in a properties file (which can be delivered with the other application files).

Let's take a brief look at how this could work. A flight simulator application is being developed. It would be sensible if the simulator associated a red "stop" button with key regions of the western part of the world. To add this red button, the developer would begin by defining the appropriate property. The file would be named something like "flightsim.stop.color=#ff0000". It would be stored in a folder with a title such as "flightsim.properties."

The code that will accomplish the upload of the property file as a ResourceBundle1 and set the property color is:

ResourceBundle resources = null;
Color stopColor = Color.red
try {
resources = ResourceBundle.getBundle("flightsim");
String colorString = resources.getString("flightsim.stop.color");
stopColor = Color.decode(colorString);
} catch (MissingResourceException missingException) {
// Report the error, according to severity
}
// stopColor has now been customized

For most developers, the existence of a properties file is transparent. This file provides an important ability to override default values. To customize application properties, the developer only needs to edit the properties file.

Code example taken from Developing Accessible JFC Applications, available at: http://www.sun.com/access/developers/developing-accessible-apps/.

Provision H

§1194.21(h) “When animation is displayed, the information shall be displayable in at least one non-animated presentation mode at the option of the user.”

Your application should provide an option that enables users to stop animation. In addition, it should also provide an alternative (or redundant) way of presenting the information in a non-animated format. An example of this is to provide a user with the option of reading a text status message (on the status line) or viewing an animated icon.

MediaTracker can be used to track the status of a number of media objects. Media objects can include audio clips as well as images (although only images are currently supported). To use a media tracker, create an instance of MediaTracker and call its addImage method for each image to be tracked. This code depicts the use of MediaTracker to stop the animation:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.MediaTracker;

public class ImageBlaster extends Applet implements Runnable {
   MediaTracker tracker;
   Image bg;
   Image anim[] = new Image[5];
   int index;
   Thread animator;

// Get the images for the background (id == 0) and the animation frames (id == 1)
   // and add them to the MediaTracker
   public void init() {
      tracker = new MediaTracker(this);
      bg = getImage(getDocumentBase(), "images/background.gif");
      tracker.addImage(bg, 0);
      for (int i = 0; i < 5; i++) {
         anim[i] = getImage(getDocumentBase(), "images/anim"+i+".gif");
	          tracker.addImage(anim[i], 1);
      }
   }

   // Start the animation thread.
   public void start() {
      animator = new Thread(this);
      animator.start();
   }
   // Stop the animation thread.
   public void stop() {
      animator = null;
   }
// Run the animation thread.
   // First wait for the background image to fully load and paint.  Then wait for all of
   // the animation frames to finish loading. Finally, loop and increment the
   // animation frame index.
   public void run() {
      try {
         tracker.waitForID(0);
         tracker.waitForID(1);
      } catch (InterruptedException e) {
         return;
      }

      Thread me = Thread.currentThread();
      while (animator == me) {
         try {
            Thread.sleep(100);
         } catch (InterruptedException e) {
            break;
         }
         synchronized (this) {

            index++;
if (index >= anim.length) {
   index = 0;
}
         }
         repaint();
      }
   }
   // The background image fills the frame so we don't need to clear the applet on
   // repaints.  Just call the paint method.
   public void update(Graphics g) {
      paint(g);
   }
   // Paint a large red rectangle if there are any errors loading the images.  Otherwise
   // always paint the background so that it appears incrementally as it is loading.
   // Finally,   only paint the current animation frame if all of the frames (id == 1) are done
   // loading, so that we don't get partial animations.
   public void paint(Graphics g) {
      if ((tracker.statusAll(false) & MediaTracker.ERRORED) != 0) {
         g.setColor(Color.red);
         g.fillRect(0, 0, size().width, size().height);
         return;
      }
      g.drawImage(bg, 0, 0, this);
      if (tracker.statusID(1, false) == MediaTracker.COMPLETE) {
         g.drawImage(anim[index], 10, 10, this);
      }
   }
}

Provision I

§1194.21(i) “Color coding shall not be used as the only means of conveying information, indicating an action, prompting a response, or distinguishing a visual element.”

Color should be used only as an enhancement. It should never be the sole means of conveying information or indicating the need for user action. If color is used to communicate information or action, then one or more of these approaches should also be utilized:

Provision J

§1194.21(j) “When a product permits a user to adjust color and contrast settings, a variety of color selections capable of producing a range of contrast levels shall be provided.”

Two programming techniques can be utilized in Java that will assist you in conforming to this provision. Both techniques allow the developer to provide the user with:

Let's begin our review of utilizing Java techniques by looking at a simple way to provide the user with multiple color selections.

Multiple Color Selections
If color customization is supported by your application, then you need to provide the user with several background and foreground color selections from which to choose. Ensure that a range of high contrast settings are offered.

One way that color selections can be provided is to use the JFC component "JColorChooser." This component can be placed anywhere within the application’s GUI. In addition, the JColorChooser API provides a method to bring up a dialog that contains the color chooser itself.

This piece of sample code features the use of JcolorChooser1:

//Set up banner to use as custom preview panel
final JLabel banner = new JLabel("Welcome to the Tutorial Zone!",
                                         JLabel.CENTER);
banner.setForeground(Color.yellow);
…

JPanel bannerPanel = new JPanel(new BorderLayout());
bannerPanel.add(banner, BorderLayout.CENTER);
bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));

//Set up color chooser for setting background color
JPanel panel = new JPanel();
JButton bcc = new JButton("Show Color Chooser...");
bcc.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
                    Color newColor = JColorChooser.showDialog(
                                                ColorChooserDemo2.this,
                                                "Choose Background Color",
                                                banner.getBackground());
                    if (newColor != null) {
                        banner.setBackground(newColor);
                    }
}
});

panel.add(bcc);
panel.setBorder(BorderFactory.createTitledBorder("Choose Background Color"));

//Set up color chooser for setting text color
final JColorChooser tcc = new JColorChooser();
tcc.getSelectionModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
	Color newColor = tcc.getColor();
                    	banner.setForeground(newColor);
}
});

tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
…
Container contentPane = getContentPane();
contentPane.add(bannerPanel, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);
…

1 Code example taken from The Java Tutorial available at: http://java.sun.com/docs/books/tutorial/uiswing/components/colorchooser.html.

Custom Colors and Fonts
Some applications may require or benefit from the use of specialized colors or fonts for specific objects. In these cases, the values should be stored in a properties file (which can be delivered with other application files).,/p>

Let's take a look at an example. For the sake of this discussion, we will talk about a developer who is working on an application that simulates piloting a jumbo jet. The designer has created an interactive segment that features red "stop" buttons located on a navigation panel. The developer would create this button by defining the appropriate property. Let's use this file name as an example:

flightsim.stop.color=#ff0000

The file would be stored in a folder called flightsim.properties. Once this is done, the program can then load the properties file as a ResourceBundle2. This code is used to load the ResourceBundle:

ResourceBundle resources = null;
Color stopColor = Color.red;
try {
resources = ResourceBundle.getBundle("flightsim");
String colorString = resources.getString("flightsim.stop.color");
stopColor = Color.decode(colorString);
} catch (MissingResourceException missingException) {
// Report the error, according to severity
}
// stopColor has now been customized

The existence of a properties file is transparent to most developers, but it provides the important ability to override default values. In order to customize the properties, the user need only edit the properties.

2 Code example taken from Developing Accessible JFC Applications available at: http://www.sun.com/access/developers/developing-accessible-apps/.

Provision K

§1194.21(k) “Software shall not use flashing or blinking text, objects, or other elements having a flash or blink frequency greater than 2 Hz and lower than 55 Hz.”>

Java developers can utilize a programming option that enables users to slow down or disable flashing screen items.

For applications utilizing Windows, the caret blink rate should be used to flash information. The user can adjust the blink rate through the Control Panel.

Identified information will flash 1.2 times per second if the cursor blink rate is set to "slow." The flash rate will increase, 100 milliseconds per notch, to a maximum of five times per second. You can query the setting by calling getCaretBlinkTime using this code:

...
//where initialization occurs
CaretListenerLabel caretListenerLabel = new CaretListenerLabel("Caret Status");
...
textPane.addActionListener(caretListenerLabel);
...
protected class CaretListenerLabel extends JLabel
implements CaretListener
{
...
public void caretUpdate(CaretEvent e) {
//Get the location in the text
int dot = e.getDot();
int mark = e.getMark();
        	int blinktime = e.getCaretBlinkTime();
		...
    	}
}

Provision L

§1194.21(l) “When electronic forms are used, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues.”

If your application uses electronic forms, and conforms to all other provisions discussed, then it will also be structured so that it conforms to this provision. To make the form accessible, the application should:

All components used in electronic forms should use the Java Accessibility API. Support for the Java Accessiblity API is built into the standard form elements provided with JFC/Swing (such as text fields, list boxes, check boxes and radio boxes). All custom components should implement the Accessible interface.

Let's take a look at some example code for an electronic form. This code is structured so that it features many of the qualities just discussed:

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

public class AccessibleForm
{
static JTextField nameTextField = new JTextField();

   	public Component createComponents() {
		// Create Labels
       		final JLabel label = new JLabel("Register Now!");
        		final JLabel emptyLabel = new JLabel("");

       		final JLabel nameLabel = new JLabel("Name: ");
		nameLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_N);
		final JLabel emailLabel = new JLabel("Email: ");
		emailLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_E);
        		final JLabel phoneLabel = new JLabel("Phone: ");
		phoneLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_P);
final JLabel typeLabel = new JLabel("Membership Type: ");
		typeLabel.setDisplayedMnemonic(java.awt.event.KeyEvent.VK_M);

		// Create text fields
		JTextField emailTextField = new JTextField();
        	JTextField phoneTextField = new JTextField();

		// Create list box
		String[] types = {"Family", "Couple", "Single", "Other"};
		JComboBox membershipTypesComboBox = new JComboBox(types);

		// Create Button
	JButton button = new JButton(new ImageIcon("register.gif"));
        	button.setMnemonic(KeyEvent.VK_R);
		button.setToolTipText("Register");
		// If tool tip is being used for something else, set the accessible name.
		button.getAccessibleContext().setAccessibleName("Register Button");
		button.getAccessibleContext().setAccessibleDescription("Click this button
			to register.");

		button.addActionListener(new ActionListener() {
            		public void actionPerformed(ActionEvent e) {
                		// Do registration
            		}
        	});

		// Set relationships between labels and other components
        	label.setLabelFor(button);
        	nameLabel.setLabelFor(nameTextField);
        	emailLabel.setLabelFor(emailTextField);
        	phoneLabel.setLabelFor(phoneTextField);
       		typeLabel.setLabelFor(membershipTypesComboBox);

		// Create JPanel and add the components
        	JPanel pane = new JPanel();
       		pane.setLayout(new GridLayout(6, 2));
        	pane.add(label);
        	]pane.add(emptyLabel);
        	pane.add(nameLabel);
        	pane.add(nameTextField);
       		pane.add(emailLabel);
        	pane.add(emailTextField);
        	pane.add(phoneLabel);
        	pane.add(phoneTextField);
        	pane.add(typeLabel);
	pane.add(membershipTypesComboBox);
        	pane.add(button);
        	return pane;
    	}

    	public static void main(String[] args) {

		try {
UIManager.setLookAndFeel(
                		UIManager.getCrossPlatformLookAndFeelClassName());
        	} catch (Exception e) { }

		//Create the top-level container and add contents to it.
        	JFrame frame = new JFrame("Accessible Form");
        	AccessibleForm accessForm = new AccessibleForm();
        	Component contents = accessForm.createComponents();
        	frame.getContentPane().add(contents, BorderLayout.CENTER);

        	//Finish setting up the frame, and show it.
        	frame.addWindowListener(new WindowAdapter() {
	       		public void windowClosing(WindowEvent e) {
                		System.exit(0);
        		}
            	});

		// Add a Window listener to the JFrame that requests the text field to have focus
		// when the window is activated
		frame.addWindowListener(new WindowAdapter() {
			public void windowActive() {
				nameTextField.requestFocus();
			}
		});

       		frame.pack();
        	frame.setVisible(true);
    	}
}