IT干货网

Java Swing Shift+F10 辅助功能

luoye11 2024年11月24日 编程设计 78 0

根据可访问性要求,Shift+F10 应该可以打开右键单击上下文菜单。

在 Swing 中,一种方法是将键绑定(bind)添加到您创建的每个组件。但是,我已经尝试扩展 EventQueue 以处理所有 Shift+F10 按下。特别是,我重写了 dispatchEvent(AWTEvent) 以将 Shift+F10 KeyEvents 转换为右键单击 mousePresses:

protected void dispatchEvent(AWTEvent event) { 
    if (event instanceof KeyEvent) { 
        KeyEvent ev = (KeyEvent) event; 
        if ((ev.getKeyCode() == KeyEvent.VK_F10) &&  
                    (ev.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) > 0) { 
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); 
            Component comp = kfm.getFocusOwner(); 
            Point mouse = MouseInfo.getPointerInfo().getLocation(); 
            SwingUtilities.convertPointFromScreen(mouse, comp); 
 
            eventToDispatch = new MouseEvent(comp, 
                            MouseEvent.MOUSE_RELEASED, ev.getWhen(), 0, mouse.x, mouse.y,  
                            1, true); 
        } 
   } 
} 

但是,这会阻止 Shift+F10 关闭任何已启动的 JPopupMenus。知道这个解决方案是否可行,或者是否有更好的方法来满足这个要求?

请您参考如下方法:

ActionListener actionListener = new ActionListener() { 
      public void actionPerformed(ActionEvent actionEvent) { 
        try { 
          int dotPosition = textField.getCaretPosition(); 
          Rectangle popupLocation = textField 
              .modelToView(dotPosition); 
          popup.show(textField, popupLocation.x, popupLocation.y); 
        } catch (BadLocationException badLocationException) { 
          System.out.println("Oops"); 
        } 
      } 
    }; 
    KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_F10, 
        InputEvent.SHIFT_MASK); 
    textField.registerKeyboardAction(actionListener, keystroke, 
        JComponent.WHEN_FOCUSED); 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!