Java/Swing JFC/Accessible

Материал из Java эксперт
Перейти к: навигация, поиск

A GUI to show accessible information coming from the components in an

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// AssistiveExample.java //A GUI to show accessible information coming from the components in an //application. See BigExample.java for example of how to use this class. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.accessibility.*; import javax.accessibility.util.*; public class BigExample extends JFrame {

 public BigExample() {
   super("Big Accessibility Example");
   setSize(700,500);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   JMenuBar jmb = new JMenuBar();
   JMenu fileMenu = new JMenu("File");
   JMenuItem openItem = new JMenuItem("Open");
   JMenuItem saveItem = new JMenuItem("Save");
   JMenuItem exitItem = new JMenuItem("Exit");
   exitItem.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
       System.exit(0);
     }
   });
   fileMenu.add(openItem);
   fileMenu.add(saveItem);
   fileMenu.add(new JSeparator());
   fileMenu.add(exitItem);
   jmb.add(fileMenu);
   setJMenuBar(jmb);
   JTextArea jta = new JTextArea("[Notes]\n");
   JScrollPane sp1 = new JScrollPane(jta);
   sp1.setMinimumSize(new Dimension(200,200));
   sp1.setPreferredSize(new Dimension(200,200));
   String[] titles = { "Name", "Start Date", "Job Title" };
   String[][] data = {
     {"Jordan", "2001", "Director"},
     {"Naveen", "1999", "Programmer"},
     {"Jia", "2000", "Analyst"},
     {"Brooks", "1998", "Evangelist"}
   };
   JTable table = new JTable(data, titles);
   table.getAccessibleContext().setAccessibleDescription("Employee Statistics");
   JPanel rightPane = new JPanel(new BorderLayout());
   rightPane.add(new JScrollPane(table), BorderLayout.CENTER);
   rightPane.add(new JLabel(new ImageIcon("logo.gif")), BorderLayout.SOUTH);
   JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp1, rightPane);
   getContentPane().add(jsp, BorderLayout.CENTER);
   JPanel bPane = new JPanel();
   JButton okButton = new JButton("Ok");
   JButton applyButton = new JButton("Apply");
   JButton clearButton = new JButton("Clear");
   bPane.add(okButton);
   bPane.add(applyButton);
   bPane.add(clearButton);
   getContentPane().add(bPane, BorderLayout.SOUTH);
   setVisible(true);
 }
 public static void main(String args[]) {
   new BigExample();
   new AssistiveExample();
 }

}

class AssistiveExample extends JPanel implements MouseMotionListener,

   ActionListener, GUIInitializedListener {
 Timer timer;
 static JFrame frame;
 JLabel nameLabel = new JLabel();
 JLabel descriptionLabel = new JLabel();
 JLabel tableLabel = new JLabel();
 JCheckBox selectionCheckBox = new JCheckBox("Selection", false);
 JCheckBox textCheckBox = new JCheckBox("Text", false);
 JCheckBox valueCheckBox = new JCheckBox("Value", false);
 JCheckBox componentCheckBox = new JCheckBox("Component", false);
 JCheckBox actionCheckBox = new JCheckBox("Action", false);
 JCheckBox hypertextCheckBox = new JCheckBox("Hypertext", false);
 JCheckBox iconCheckBox = new JCheckBox("Icon", false);
 JCheckBox tableCheckBox = new JCheckBox("Table", false);
 JCheckBox editableTextCheckBox = new JCheckBox("EditableText", false);
 JLabel classLabel = new JLabel();
 JLabel parentLabel = new JLabel();
 JLabel relationLabel = new JLabel();
 JButton performAction = new JButton("Perform Action");
 public AssistiveExample() {
   frame = new JFrame("Assistive Example");
   // Insert the appropriate labels and check boxes
   setLayout(new GridLayout(0, 1)); // just make as many rows as we need
   add(nameLabel);
   add(descriptionLabel);
   add(tableLabel);
   add(new JSeparator());
   add(actionCheckBox);
   add(componentCheckBox);
   add(editableTextCheckBox);
   add(hypertextCheckBox);
   add(iconCheckBox);
   add(selectionCheckBox);
   add(tableCheckBox);
   add(textCheckBox);
   add(valueCheckBox);
   add(classLabel);
   add(parentLabel);
   add(relationLabel);
   add(performAction);
   setBorder(new TitledBorder("Accessible Component"));
   performAction.addActionListener(this);
   frame.getContentPane().add(this, BorderLayout.CENTER);
   frame.setBounds(100, 100, 500, 600);
   frame.setVisible(true);
   //  Check to see if the GUI subsystem is initialized
   //  correctly. (This is needed in JDK 1.2 and higher).
   //  If it isn"t ready, then we have to wait.
   if (EventQueueMonitor.isGUIInitialized()) {
     createGUI();
   } else {
     EventQueueMonitor.addGUIInitializedListener(this);
   }
   performAction.grabFocus();
 }
 public void guiInitialized() {
   createGUI();
 }
 public void createGUI() {
   //  We want to track the mouse motions, so notify the
   //  Swing event monitor of this.
   SwingEventMonitor.addMouseMotionListener(this);
   //  Start a Timer object to measure how long the mouse stays
   //  over a particular area.
   timer = new Timer(500, this);
 }
 public void mouseMoved(MouseEvent e) {
   //  If the mouse moves, restart the timer.
   timer.restart();
 }
 public void mouseDragged(MouseEvent e) {
   //  If the mouse is dragged, restart the timer.
   timer.restart();
 }
 public void actionPerformed(ActionEvent e) {
   //Find the component currently under the mouse.
   Point currentPosition = EventQueueMonitor.getCurrentMousePosition();
   Accessible comp = EventQueueMonitor.getAccessibleAt(currentPosition);
   //If the user pressed the button, and the component
   //has an accessible action, then execute it.
   if (e.getActionCommand() == "Perform Action") {
     AccessibleContext context = comp.getAccessibleContext();
     AccessibleAction action = context.getAccessibleAction();
     if (action != null)
       action.doAccessibleAction(0);
     else
       System.out.println("No accessible action present!");
     return;
   }
   //  Otherwise, the timer has fired. Stop it and update the window.
   timer.stop();
   updateWindow(comp);
 }
 private void updateWindow(Accessible component) {
   if (component == null) {
     return;
   }
   // Reset the check boxes
   actionCheckBox.setSelected(false);
   selectionCheckBox.setSelected(false);
   textCheckBox.setSelected(false);
   componentCheckBox.setSelected(false);
   valueCheckBox.setSelected(false);
   hypertextCheckBox.setSelected(false);
   iconCheckBox.setSelected(false);
   tableCheckBox.setSelected(false);
   editableTextCheckBox.setSelected(false);
   // Get the accessibile context of the component in question
   AccessibleContext context = component.getAccessibleContext();
   AccessibleRelationSet ars = context.getAccessibleRelationSet();
   nameLabel.setText("Name: " + context.getAccessibleName());
   descriptionLabel.setText("Desc: " + context.getAccessibleDescription());
   relationLabel.setText("Relation: " + ars);
   // Check the context for each of the accessibility types
   if (context.getAccessibleAction() != null)
     actionCheckBox.setSelected(true);
   if (context.getAccessibleSelection() != null)
     selectionCheckBox.setSelected(true);
   if (context.getAccessibleText() != null) {
     textCheckBox.setSelected(true);
     if (context.getAccessibleText() instanceof AccessibleHypertext)
       hypertextCheckBox.setSelected(true);
   }
   if (context.getAccessibleComponent() != null) {
     componentCheckBox.setSelected(true);
     classLabel.setText("Class: " + context.getAccessibleComponent());
     parentLabel.setText("Parent: " + context.getAccessibleParent());
   }
   if (context.getAccessibleValue() != null)
     valueCheckBox.setSelected(true);
   if (context.getAccessibleIcon() != null)
     iconCheckBox.setSelected(true);
   if ((context.getAccessibleTable() != null)
       || (context.getAccessibleParent() instanceof JTable)) {
     tableCheckBox.setSelected(true);
     tableLabel.setText("Table Desc: "
         + context.getAccessibleParent().getAccessibleContext()
             .getAccessibleDescription());
   } else {
     tableLabel.setText("");
   }
   // On 1.4+ systems, you can check for editable text with these two
   // lines.
   // Note that because of the 1.4 restriction, these lines will not
   // compile
   // on a Mac system as of the time of this writing. You can comment out
   // these lines and still compile/run the example, though.
   //if (context.getAccessibleEditableText() != null)
   //  editableTextCheckBox.setSelected(true);
   repaint();
 }

}


 </source>
   
  
 
  



An example of getting the Accessible information from a Button object

   <source lang="java">

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// ActionExampleButton.java //An example of getting the Accessible information from a Button object. //(You could see this information by attaching an AssistiveExample object //to the button. See BigExample.java for an example of that attachment.) // import java.awt.BorderLayout; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Locale; import javax.accessibility.Accessible; import javax.accessibility.AccessibleAction; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.accessibility.AccessibleStateSet; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class ActionExample extends Button implements ActionListener, Accessible {

 public ActionExample() {
   super("Press this Button");
   addActionListener(this);
 }
 public AccessibleContext getAccessibleContext() {
   return (new ActionAccessibleContext());
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("The button was pressed!");
 }
 public void processActionEvent(ActionEvent e) {
   super.processActionEvent(e);
 }
 // This class contains the accessible context for the component. Many
 // abstract methods simply call the SwingUtilities class to get the job
 // done; this is advised if you can get away with it. Otherwise, see the
 // source code for SwingUtilities.
 class ActionAccessibleContext extends AccessibleContext {
   public ActionAccessibleContext() {
     super();
     setAccessibleName("Button");
     setAccessibleDescription("Press the Button");
   }
   public AccessibleRole getAccessibleRole() {
     // Fill in whatever role you want here
     return (AccessibleRole.AWT_COMPONENT);
   }
   public AccessibleStateSet getAccessibleStateSet() {
     return SwingUtilities.getAccessibleStateSet(ActionExample.this);
   }
   public int getAccessibleIndexInParent() {
     return SwingUtilities
         .getAccessibleIndexInParent(ActionExample.this);
   }
   public int getAccessibleChildrenCount() {
     return SwingUtilities
         .getAccessibleChildrenCount(ActionExample.this);
   }
   public Accessible getAccessibleChild(int i) {
     return SwingUtilities.getAccessibleChild(ActionExample.this, i);
   }
   public Locale getLocale() {
     //  Ask the component what its locale is
     return ActionExample.this.getLocale();
   }
   public AccessibleAction getAccessibleAction() {
     return new AccessAction();
   }
 }
 // This class implements the AccessibleAction interface. Essentially, there
 // is only one action that is the equivalent of pushing the button.
 class AccessAction implements AccessibleAction {
   final int NUMBER_OF_ACTIONS = 1;
   final String DESCRIPTION = "Presses the button";
   public int getAccessibleActionCount() {
     return NUMBER_OF_ACTIONS;
   }
   public String getAccessibleActionDescription(int i) {
     if (i == 0)
       return (DESCRIPTION);
     else
       return null;
   }
   public boolean doAccessibleAction(int i) {
     if (i == 0) {
       // Simulate pressing a button
       ActionExample.this.processActionEvent(new ActionEvent(this,
           ActionEvent.ACTION_PERFORMED, ActionExample.this
               .getActionCommand()));
       return true;
     } else
       return false;
   }
 }
 public static void main(String s[]) {
   ActionExample example = new ActionExample();
   JFrame frame = new JFrame("AccessibleAction Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(example, BorderLayout.CENTER);
   frame.setSize(100, 100);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Associating a Label with a Component

   <source lang="java">

import javax.swing.JLabel; import javax.swing.JTextField; public class Main {

 public static void main(String[] argv) throws Exception {
   JTextField component = new JTextField();
   JLabel label = new JLabel("Name:");
   label.setDisplayedMnemonic("N");
   label.setLabelFor(component);
 }

}

 </source>
   
  
 
  



Has Displayed Name

   <source lang="java">
  

import javax.swing.AbstractButton; import javax.swing.JLabel; import javax.swing.text.JTextComponent;

public class Util {

 public static boolean hasDisplayedName(Class componentClass) {
   return ((AbstractButton.class.isAssignableFrom(componentClass))
           || (JLabel.class.isAssignableFrom(componentClass))
           || (JTextComponent.class.isAssignableFrom(componentClass))
   );
 }

}


 </source>
   
  
 
  



implement Accessible to make your object accessible

   <source lang="java">

import java.awt.IllegalComponentStateException; import java.util.Locale; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.accessibility.AccessibleStateSet; public class Main implements Accessible {

 public AccessibleContext getAccessibleContext() {
   return new AccessibleContext() {
     @Override
     public AccessibleRole getAccessibleRole() {
       return null;
     }
     @Override
     public AccessibleStateSet getAccessibleStateSet() {
       return null;
     }
     @Override
     public int getAccessibleIndexInParent() {
       return 0;
     }
     @Override
     public int getAccessibleChildrenCount() {
       return 0;
     }
     @Override
     public Accessible getAccessibleChild(int i) {
       return null;
     }
     @Override
     public Locale getLocale() throws IllegalComponentStateException {
       return null;
     }
   };
 }

}

 </source>
   
  
 
  



Setting a Description for Image Icons

   <source lang="java">

import javax.swing.ImageIcon; public class Main {

 public static void main(String[] argv) throws Exception {
   ImageIcon icon = new ImageIcon("image.gif");
   icon.setDescription("Description of Image");
 }

}

 </source>
   
  
 
  



Setting a Keyboard Accelerator for a Menu Item

   <source lang="java">

import java.awt.event.KeyEvent; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JMenuItem item = new JMenuItem("Item");
   item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.SHIFT_MASK));
 }

}

 </source>
   
  
 
  



Setting a Mnemonic for a Menu for Accessible

   <source lang="java">

import javax.swing.JMenu; public class Main {

 public static void main(String[] argv) throws Exception {
   JMenu menu = new JMenu("Menu");
   menu.setMnemonic("M");
 }

}

 </source>
   
  
 
  



Setting a Mnemonic for Buttons for Accessible

   <source lang="java">

import javax.swing.JButton; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton button = new JButton("Button");
   button.setMnemonic("B");
   JCheckBox checkBox = new JCheckBox("CheckBox");
   checkBox.setMnemonic("C");
 }

}

 </source>
   
  
 
  



Setting an Accessible Name for an Image Button

   <source lang="java">

import javax.swing.ImageIcon; import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
 JButton button = new JButton(new ImageIcon("image.gif"));
   button.setToolTipText("Button Name");
   button.getAccessibleContext().setAccessibleName("Button Name");
 }

}

 </source>