在 Swing 中,某些复杂组件(如 JTree 、 JTable 、 JList 和 JComboBox )不直接呈现其内容。而是将此任务委托给由 呈现程序创建的组件。呈现程序是一个工厂对象,它创建一个组件,用来创建显示复杂组件的行/单元值的组件。该组件仅在绘制行/单元的短暂时间内使用。通过提供定制的组件,您可以控制如何将行/单元呈现给用户,包括提供由 AT 阅读器使用的可访问信息。
由呈现程序生成的组件需要和我们迄今为止所讨论过的比较简单的组件一样,对于用户是可访问的,这意味着我们必须能够设置其可访问性值。在 Swing 中,我们通常通过创建 xxxCellRenderer 子类来做到这一点,其中 xxx 是基本组件类型。清单 14 显示了 JList 的单元呈现程序。请注意实际使用的工具箱的助手类。
清单 14. JList 的单元呈现程序
1 class DemoListCellRenderer implements ListCellRenderer {
2 protected ListCellRenderer _lcr = new DefaultListCellRenderer();
3 public Component getListCellRendererComponent(
4 JList list,
5 Object value,
6 int index,
7 boolean isSelected,
8 boolean cellHasFocus) {s
9 String name = value.toString();
10 String shortDesc =
11 AccessibleUtils.formatText(resourceBundle, "months {0}", name);
12 String longDesc =
13 AccessibleUtils.formatText(resourceBundle, "Selects month {0}",
14 (String)_monthsMap.get(name.substring(0,3)));
15 JComponent c = (JComponent)_lcr.getListCellRendererComponent(
16 list,
17 name,
18 index,
19 isSelected,
20 cellHasFocus);
21 return (Component)AccessibleUtils.setAccessibleValues(
22 resourceBundle, (Accessible)c,
23 new AccessibleUtils.AccessibleValues(
24 idGen.nextId("label"),
25 name,
26 shortDesc, longDesc, "=ld"));
27 }
28 }
29
2 protected ListCellRenderer _lcr = new DefaultListCellRenderer();
3 public Component getListCellRendererComponent(
4 JList list,
5 Object value,
6 int index,
7 boolean isSelected,
8 boolean cellHasFocus) {s
9 String name = value.toString();
10 String shortDesc =
11 AccessibleUtils.formatText(resourceBundle, "months {0}", name);
12 String longDesc =
13 AccessibleUtils.formatText(resourceBundle, "Selects month {0}",
14 (String)_monthsMap.get(name.substring(0,3)));
15 JComponent c = (JComponent)_lcr.getListCellRendererComponent(
16 list,
17 name,
18 index,
19 isSelected,
20 cellHasFocus);
21 return (Component)AccessibleUtils.setAccessibleValues(
22 resourceBundle, (Accessible)c,
23 new AccessibleUtils.AccessibleValues(
24 idGen.nextId("label"),
25 name,
26 shortDesc, longDesc, "=ld"));
27 }
28 }
29
如您所见,从可访问性的观点看,使用呈现程序提供的组件非常类似于使用普通的组件。尽管本讨论只展示了如何向呈现程序添加可访问性支持,但用于可编辑的行或单元的编辑器也需要类似的考虑事项。请参阅 源代码以了解更多关于工具箱对呈现复杂组件的支持。