access.html

来自「jsf、swing的官方指南」· HTML 代码 · 共 1,331 行 · 第 1/4 页

HTML
1,331
字号
</blockquote><a name="namesdescriptions"><h3>Setting Accessible Names and Descriptions on Components</h3></a><blockquote>Giving your program's components accessible names and descriptionsis one of the easiest and most important stepsin making your program accessible.Following is a complete listingof the <code>AccessibleScrollDemo</code> constructor thatcreates the scroll pane and the custom components it uses.The boldface statements give components names and descriptionsthat assistive technologies can use.<blockquote><pre>public AccessibleScrollDemo() {    // Get the image to use.    <b>ImageIcon david = createImageIcon("images/youngdad.jpeg",                      "Photograph of David McNabb in his youth.");</b>    // Create the row and column headers.    columnView = new Rule(Rule.HORIZONTAL, true);    if (david != null) {        columnView.setPreferredWidth(david.getIconWidth());    } else {        columnView.setPreferredWidth(320);    }    <b>columnView.getAccessibleContext().setAccessibleName("Column Header");</b>    <b>columnView.getAccessibleContext().            setAccessibleDescription("Displays horizontal ruler for " +                                     "measuring scroll pane client.");</b>    rowView = new Rule(Rule.VERTICAL, true);    if (david != null) {        rowView.setPreferredHeight(david.getIconHeight());    } else {        rowView.setPreferredHeight(480);    }    <b>rowView.getAccessibleContext().setAccessibleName("Row Header");</b>    <b>rowView.getAccessibleContext().            setAccessibleDescription("Displays vertical ruler for " +                                     "measuring scroll pane client.");</b>    // Create the corners.    JPanel buttonCorner = new JPanel();    isMetric = new JToggleButton("cm", true);    isMetric.setFont(new Font("SansSerif", Font.PLAIN, 11));    isMetric.setMargin(new Insets(2,2,2,2));    isMetric.addItemListener(this);    <b>isMetric.setToolTipText("Toggles rulers' unit of measure " +                            "between inches and centimeters.");</b>    buttonCorner.add(isMetric); //Use the default FlowLayout    <b>buttonCorner.getAccessibleContext().                 setAccessibleName("Upper Left Corner");</b>    <b>String desc = "Fills the corner of a scroll pane " +                  "with color for aesthetic reasons.";</b>    Corner lowerLeft = new Corner();    <b>lowerLeft.getAccessibleContext().              setAccessibleName("Lower Left Corner");</b>    <b>lowerLeft.getAccessibleContext().setAccessibleDescription(desc);</b>    Corner upperRight = new Corner();    <b>upperRight.getAccessibleContext().               setAccessibleName("Upper Right Corner");</b>    <b>upperRight.getAccessibleContext().setAccessibleDescription(desc);</b>        // Set up the scroll pane.    picture = new ScrollablePicture(david,                                    columnView.getIncrement());    <b>picture.setToolTipText(david.getDescription());</b>    <b>picture.getAccessibleContext().setAccessibleName(                                     "Scroll pane client");</b>    JScrollPane pictureScrollPane = new JScrollPane(picture);    pictureScrollPane.setPreferredSize(new Dimension(300, 250));    pictureScrollPane.setViewportBorder(            BorderFactory.createLineBorder(Color.black));    pictureScrollPane.setColumnHeaderView(columnView);    pictureScrollPane.setRowHeaderView(rowView);    // In theory, to support internationalization you would change    // UPPER_LEFT_CORNER to UPPER_LEADING_CORNER,    // LOWER_LEFT_CORNER to LOWER_LEADING_CORNER, and    // UPPER_RIGHT_CORNER to UPPER_TRAILING_CORNER.  In practice,    // bug #4467063 makes that impossible (at least in 1.4.0).    pictureScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER,                                buttonCorner);    pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER,                                lowerLeft);    pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER,                                upperRight);    // Put it in this panel.    setLayout(new BoxLayout(this, BoxLayout.X_AXIS));    add(pictureScrollPane);    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));}</pre></blockquote>Often, the program sets a component's name and description directlythrough the component's accessible context.Other times,the program sets an accessible description indirectly with tool tips.In the case of the <strong>cm</strong> toggle button,the description is set automatically tothe text on the button.</blockquote><a name="developing"> <h3>Concepts: How Accessibility Works</h3> </a> <blockquote> An object is accessible if it implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/accessibility/Accessible.html"><code>Accessible</code></a> interface.The <code>Accessible</code> interface defines just one method,<code>getAccessibleContext</code>,which returnsan <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/accessibility/AccessibleContext.html"><code>AccessibleContext</code></a> object.The <code>AccessibleContext</code> object is an intermediarythat contains the accessible information for an accessible object.The following figure shows how assistive technologies get the accessible contextfrom an accessible object and query it for information:<p><center><IMG SRC="../../figures/uiswing/misc/howaccessworks.gif" WIDTH="528" HEIGHT="190" ALIGN="BOTTOM" ALT="How assistive technologies get information from accessible objects."></center></p><p><code>AccessibleContext</code> is an abstract classthat defines the minimum set of informationan accessible object must provide about itself.The minimum set includes name, description, role,state set, and so on.To identify its accessible object as having particular capabilities,an accessible context can implement one or more of theinterfaces as shown in the <a href="#interfaceList">AccessibleInterfaces</a> table. For example, <code>JButton</code> implements<code>AccessibleAction</code>, <code>AccessibleValue</code>,<code>AccessibleText</code>, and <code>AccessibleExtendedComponent</code>.It is not necessary for <code>JButton</code> to implement<code>AccessibleIcon</code> because that is implemented bythe <code>ImageIcon</code> attached to the button.<p>Because the <code>JComponent</code> class itselfdoes not implement the <code>Accessible</code> interface,instances of its direct subclasses are not accessible.If you write a custom component that inherits directlyfrom <code>JComponent</code>,you need to explicitly make itimplement the <code>Accessible</code> interface.<code>JComponent</code> does have an accessible context,called <code>AccessibleJComponent</code>,that implements the <code>AccessibleComponent</code>interface and provides a minimal amount of accessible information.You can provide an accessible context for your customcomponents by creating a subclass of <code>AccessibleJComponent</code>and overriding important methods.<a href="#accessiblecomponents">Making Custom Components Accessible</a>shows two examples of doing this.<p>All the other standard Swing componentsimplement the <code>Accessible</code> interface andhave an accessible context that implementsone or more of the preceding interfaces as appropriate.The accessible contexts for Swing componentsare implemented as inner classesand have names of this style:<blockquote><pre><em>Component</em>.Accessible<em>Component</em></pre></blockquote>If you create a subclass of a standard Swing componentand your subclass is substantially different from its superclass,then you should provide a custom accessible context for it.The easiest way is to create a subclassof the superclass's accessible context classand override methods as necessary.For example, if you create a <code>JLabel</code> subclasssubstantially different from <code>JLabel</code>,then your <code>JLabel</code> subclass should contain an inner classthat extends <code>AccessibleJLabel</code>.The next section shows how to do so,using examples in which <code>JComponent</code> subclassesextend <code>AccessibleJComponent</code>.</blockquote><a name="accessiblecomponents"> <h3>Making Custom Components Accessible</h3> </a> <blockquote> The scroll demo program uses three custom component classes.<code>ScrollablePicture</code> is a subclass of <code>JLabel</code>,and <code>Corner</code> and <code>Rule</code>are both subclasses of <code>JComponent</code>.<p>The <code>ScrollablePicture</code> classrelies completely on accessibilityinherited from <code>JLabel</code> through<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JLabel.AccessibleJLabel.html"><code>JLabel.AccessibleJLabel</code></a>.The code that creates an instance of <code>ScrollablePicture</code>sets the tool-tip text for the scrollable picture.The tool-tip text is used by the context as the component'saccessible description.This behavior is provided by <code>AccessibleJLabel</code>.<p>The accessible version of the<code>Corner</code> class contains just enough codeto make its instances accessible.We implemented accessibility supportby adding the code shown in boldto the original version of <code>Corner</code>.<blockquote><pre>public class Corner extends JComponent <strong>implements Accessible</strong> {    protected void paintComponent(Graphics g) {        //Fill me with dirty brown/orange.        g.setColor(new Color(230, 163, 4));        g.fillRect(0, 0, getWidth(), getHeight());    }    <strong>public AccessibleContext getAccessibleContext() {        if (accessibleContext == null) {            accessibleContext = new AccessibleCorner();        }        return accessibleContext;    }    protected class AccessibleCorner extends AccessibleJComponent {        //Inherit everything, override nothing.    }</strong>}</pre></blockquote>All of the accessibility provided by this classis inherited from<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.AccessibleJComponent.html"><code>AccessibleJComponent</code></a>.This approach is fine for <code>Corner</code>because <code>AccessibleJComponent</code> providesa reasonable amount of default accessibility informationand because corners are uninteresting&#151they exist only to take up a little bit of space onscreen.Other classes, such as <code>Rule</code>,need to provide customized information.<p><code>Rule</code> provides an accessible context foritself in the same manner as <code>Corner</code>,but the context overrides two methods to provide detailsabout the component's role and state:<blockquote><pre>protected class AccessibleRuler extends AccessibleJComponent {    public AccessibleRole getAccessibleRole() {        return AccessibleRuleRole.RULER;    }    public AccessibleStateSet getAccessibleStateSet() {        AccessibleStateSet states =            super.getAccessibleStateSet();        if (orientation == VERTICAL) {            states.add(AccessibleState.VERTICAL);        } else {            states.add(AccessibleState.HORIZONTAL);        }        if (isMetric) {            states.add(AccessibleRulerState.CENTIMETERS);        } else {            states.add(AccessibleRulerState.INCHES);        }        return states;    }}</pre></blockquote><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/accessibility/AccessibleRole.html"><code>AccessibleRole</code></a> is an enumeration of objects that identify roles thatSwing components can play.It contains predefined roles such as label, button, and so on.The rulers in our example don't fit wellinto any of the predefined roles,so the program invents a new one in a subclassof <code>AccessibleRole</code>:<blockquote><pre>class AccessibleRuleRole extends AccessibleRole {    public static final AccessibleRuleRole RULER        = new AccessibleRuleRole("ruler");    protected AccessibleRuleRole(String key) {        super(key);    }    //Should really provide localizable versions of these names.    public String toDisplayString(String resourceBundleName,                                  Locale locale) {        return key;    }}</pre></blockquote>Any component that has state can provide state informationto assistive technologiesby overriding the <code>getAccessibleStateSet</code>method.A rule has two sets of states:its orientation can be either vertical or horizontal, andits units of measure can be either centimeters or inches.<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/accessibility/AccessibleState.html"><code>AccessibleState</code></a> is an enumeration of predefined states.This program uses its predefined statesfor vertical and horizontal orientation.Because <code>AccessibleState</code> contains nothingfor centimeters and inches,the program makes a subclass to provide appropriate states:<blockquote><pre>class AccessibleRulerState extends AccessibleState {    public static final AccessibleRulerState INCHES        = new AccessibleRulerState("inches");    public static final AccessibleRulerState CENTIMETERS        = new AccessibleRulerState("centimeters");    protected AccessibleRulerState(String key) {        super(key);    }    //Should really provide localizable versions of these names.    public String toDisplayString(String resourceBundleName,                                  Locale locale) {        return key;    }}</pre></blockquote>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?