Java Code Examples for javax.swing.KeyStroke#getKeyStrokeForEvent()

The following examples show how to use javax.swing.KeyStroke#getKeyStrokeForEvent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StayOpenPopupMenu.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager) {
    if (isReturnAction(e)) { // Handle SPACE and ENTER
        MenuElement[] p = manager.getSelectedPath();
        MenuElement m = p != null && p.length > 0 ? p[p.length - 1] : null;
        if (m instanceof StayOpen) {
            e.consume();
            if (e.getID() == KeyEvent.KEY_PRESSED)
                performAction((StayOpen)m, e.getModifiers());
            return;
        }
    } else for (Component component : getComponents()) { // Handle mnemonics and accelerators
        if (component instanceof StayOpen) {
            StayOpen item = (StayOpen)component;
            JMenuItem i = item.getItem();
            KeyStroke k = KeyStroke.getKeyStrokeForEvent(e);
            if (k.equals(mnemonic(i)) || k.equals(i.getAccelerator())) {
                e.consume();
                manager.setSelectedPath(new MenuElement[] { this, i });
                performAction(item, e.getModifiers());
                return;
            }
        }
    }
    
    super.processKeyEvent(e, path, manager);
}
 
Example 2
Source File: TextRegionManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void keyPressed(KeyEvent evt) {
            TextRegionManager manager = textRegionManager(evt);
            if (manager == null || !manager.isActive() || evt.isConsumed())
                return;

            KeyStroke evtKeyStroke = KeyStroke.getKeyStrokeForEvent(evt);
            if (KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0) == evtKeyStroke) {
                manager.escapeAction();
                evt.consume();

//            } else if (KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0) == evtKeyStroke) {
//                if (editing.enterAction())
//                    evt.consume();
//
//            } else if (KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0) == evtKeyStroke) {
//                if (editing.tabAction())
//                    evt.consume();
//
//            } else if (KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK) == evtKeyStroke) {
//                if (editing.shiftTabAction())
//                    evt.consume();
//
            }
        }
 
Example 3
Source File: KeySequenceInputPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void keySequenceInputFieldKeyPressed (java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keySequenceInputFieldKeyPressed
    
    String inputText = keySequenceInputField.getText();
    if (evt.getModifiers() == 0 && 
            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0).equals(KeyStroke.getKeyStrokeForEvent( evt )) &&
            inputText!=null && inputText.length()>0){
        keySequenceInputField.transferFocus();
        return;
    }
    
    evt.consume();

    String modif = KeyEvent.getKeyModifiersText( evt.getModifiers() );
    if( isModifier( evt.getKeyCode() ) ) {
        keySequenceInputField.setText( text.toString() + modif + '+' ); //NOI18N
    } else {
        KeyStroke stroke = KeyStroke.getKeyStrokeForEvent( evt );
        strokes.add( stroke );
        text.append( Utilities.keyStrokeToString( stroke ) );
        text.append( ' ' );
        keySequenceInputField.setText( text.toString() );
        firePropertyChange( PROP_KEYSEQUENCE, null, null );
    }
}
 
Example 4
Source File: PopupManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void consumeIfKeyPressInActionMap(KeyEvent e) {
    // get popup's registered keyboard actions
    ActionMap am = popup.getActionMap();
    InputMap  im = popup.getInputMap();

    // check whether popup registers keystroke
    // If we consumed key pressed, we need to consume other key events as well:
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(
            new KeyEvent((Component) e.getSource(),
                         KeyEvent.KEY_PRESSED,
                         e.getWhen(),
                         e.getModifiers(),
                         KeyEvent.getExtendedKeyCodeForChar(e.getKeyChar()),
                         e.getKeyChar(),
                         e.getKeyLocation())
    );
    Object obj = im.get(ks);
    if (shouldPopupReceiveForwardedKeyboardAction(obj)) {
        // if yes, if there is a popup's action, consume key event
        Action action = am.get(obj);
        if (action != null && action.isEnabled()) {
            // actionPerformed on key press only.
            e.consume();
        }
    }
}
 
Example 5
Source File: ImportModulePanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void listKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listKeyReleased
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(evt);
    if (ks.getKeyCode() == KeyEvent.VK_ENTER
            || ks.getKeyCode() == KeyEvent.VK_SPACE) {
        boolean packageImport = (evt.getModifiers() & InputEvent.ALT_MASK) > 0;
        boolean useFqn = (evt.getModifiers() & InputEvent.SHIFT_MASK) > 0;
        importModule(getSelected(), packageImport, useFqn);
    }
}
 
Example 6
Source File: KeyStrokeDisplay.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void keyPressed(KeyEvent event) {
    KeyStroke ks   = KeyStroke.getKeyStrokeForEvent(event);
    int       code = ks.getKeyCode();
    if (code != VK_SHIFT && code != VK_CONTROL && code != VK_META && code != VK_ALT && code != VK_CAPS_LOCK && code != VK_ESCAPE) {
        mKeyStroke = ks;
        setText(getKeyStrokeDisplay(mKeyStroke));
    }
}
 
Example 7
Source File: ColumnModels.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void processKeyEvent(KeyEvent e) {
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(e);
    if (enter.equals(ks)) {
        // Prevent JComponent.processKeyBindings() to be called (it is called from
        // JComponent.processKeyEvent() ), notify only registered key listeners
        int id = e.getID();
        for (KeyListener keyListener : getKeyListeners()) {
            switch(id) {
              case KeyEvent.KEY_TYPED:
                  keyListener.keyTyped(e);
                  break;
              case KeyEvent.KEY_PRESSED:
                  keyListener.keyPressed(e);
                  break;
              case KeyEvent.KEY_RELEASED:
                  keyListener.keyReleased(e);
                  break;
            }
        }
        if (!e.isConsumed() && id == KeyEvent.KEY_PRESSED) {
            synchronized(listeners) {
                List<CellEditorListener> list = new ArrayList<CellEditorListener>(listeners);
                for (CellEditorListener listener : list) {
                    listener.editingStopped(new ChangeEvent(this));
                }
            }
        }
        e.consume();
    } else {
        super.processKeyEvent(e);
    }
}
 
Example 8
Source File: PopupManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override void keyPressed(KeyEvent e){
    if (e != null && popup != null && popup.isShowing()) {
        
        // get popup's registered keyboard actions
        ActionMap am = popup.getActionMap();
        InputMap  im = popup.getInputMap();
        
        // check whether popup registers keystroke
        KeyStroke ks = KeyStroke.getKeyStrokeForEvent(e);
        Object obj = im.get(ks);
        LOG.log(Level.FINE, "Keystroke for event {0}: {1}; action-map-key={2}", new Object [] { e, ks, obj }); //NOI18N
        if (shouldPopupReceiveForwardedKeyboardAction(obj)) {
            // if yes, gets the popup's action for this keystroke, perform it 
            // and consume key event
            Action action = am.get(obj);
            LOG.log(Level.FINE, "Popup component''s action: {0}, {1}", new Object [] { action, action != null ? action.getValue(Action.NAME) : null }); //NOI18N

            /* Make sure to use the popup as the source of the action, since the popup is
            also providing the event. Not doing this, and instead invoking actionPerformed
            with a null ActionEvent, was one part of the problem seen in NETBEANS-403. */
            if (SwingUtilities.notifyAction(action, ks, e, popup, e.getModifiers())) {
              e.consume();
              return;
            }
        }

        if (e.getKeyCode() != KeyEvent.VK_CONTROL &&
            e.getKeyCode() != KeyEvent.VK_SHIFT &&
            e.getKeyCode() != KeyEvent.VK_ALT &&
            e.getKeyCode() != KeyEvent.VK_ALT_GRAPH &&
            e.getKeyCode() != KeyEvent.VK_META
        ) {
            // hide tooltip if any was shown
            Utilities.getEditorUI(textComponent).getToolTipSupport().setToolTipVisible(false);
        }
    }
}
 
Example 9
Source File: GlobalHotkeyManager.java    From nextreports-designer with Apache License 2.0 5 votes vote down vote up
@Override
protected void dispatchEvent(AWTEvent event) {
    if (event instanceof KeyEvent) {
        // KeyStroke.getKeyStrokeForEvent converts an ordinary KeyEvent
        // to a keystroke, as stored in the InputMap.  Keep in mind that
        // Numpad keystrokes are different to ordinary keys, i.e. if you
        // are listening to
        KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent) event);
        if (DEBUG) {
        	System.out.println("KeyStroke = " + keyStroke);
        }
        String actionKey = (String) keyStrokes.get(keyStroke);
        if (actionKey != null) {
            if (DEBUG) {
            	System.out.println("ActionKey = " + actionKey);
            }
            Action action = actions.get(actionKey);
            if (action != null && action.isEnabled()) {
                // I'm not sure about the parameters
                action.actionPerformed(
                        new ActionEvent(event.getSource(), event.getID(),
                                actionKey, ((KeyEvent) event).getModifiers()));
                return; // consume event
            }
        }
    }
    
    super.dispatchEvent(event); // let the next in chain handle event
}
 
Example 10
Source File: ToggleProfilingPointAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void eventDispatched(AWTEvent event) {
    if (!(event instanceof KeyEvent)) return;
    
    KeyStroke eventKeyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent)event);
    if (acceleratorKeyStroke == null || eventKeyStroke == null) return;
    
    int acceleratorModifiers = acceleratorKeyStroke.getModifiers();
    if (acceleratorModifiers == 0) return;
    
    if (acceleratorModifiers != eventKeyStroke.getModifiers()) modifierKeyStateChanged();
}
 
Example 11
Source File: ShortcutAndMenuKeyEventProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean processShortcut(KeyEvent ev) {
    //ignore shortcut keys when the IDE is shutting down
    if (NbLifecycleManager.isExiting()) {
        ev.consume();
        return true;
    }
    
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(ev);
    Window w = SwingUtilities.windowForComponent(ev.getComponent());

    // don't process shortcuts if this is a help frame
    if ((w instanceof JFrame) && ((JFrame)w).getRootPane().getClientProperty("netbeans.helpframe") != null) // NOI18N
        return true;
    
    // don't let action keystrokes to propagate from both
    // modal and nonmodal dialogs, but propagate from separate floating windows,
    // even if they are backed by JDialog
    if ((w instanceof Dialog) &&
        !WindowManagerImpl.isSeparateWindow(w) &&
        !isTransmodalAction(ks)) {
        return false;
    }
    
    // Provide a reasonably useful action event that identifies what was focused
    // when the key was pressed, as well as what keystroke ran the action.
    ActionEvent aev = new ActionEvent(
        ev.getSource(), ActionEvent.ACTION_PERFORMED, Utilities.keyToString(ks));
        
    Keymap root = Lookup.getDefault().lookup(Keymap.class);
    Action a = root.getAction (ks);
    if (a != null && a.isEnabled()) {
        ActionManager am = Lookup.getDefault().lookup(ActionManager.class);
        am.invokeAction(a, aev);
        ev.consume();
        return true;
    }
    return false;
}
 
Example 12
Source File: ImportClassPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void listKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listKeyReleased
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(evt);
    if ( ks.getKeyCode() == KeyEvent.VK_ENTER || 
         ks.getKeyCode() == KeyEvent.VK_SPACE ) {
        importClass( 
                getSelected(),
                (evt.getModifiers() & (org.openide.util.Utilities.isMac() ? InputEvent.META_MASK : InputEvent.ALT_MASK)) > 0,
                (evt.getModifiers() & InputEvent.SHIFT_MASK) > 0);
    }
}
 
Example 13
Source File: WatchesColumnModels.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void processKeyEvent(KeyEvent e) {
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(e);
    if (enter.equals(ks)) {
        // Prevent JComponent.processKeyBindings() to be called (it is called from
        // JComponent.processKeyEvent() ), notify only registered key listeners
        int id = e.getID();
        for (KeyListener keyListener : getKeyListeners()) {
            switch(id) {
              case KeyEvent.KEY_TYPED:
                  keyListener.keyTyped(e);
                  break;
              case KeyEvent.KEY_PRESSED:
                  keyListener.keyPressed(e);
                  break;
              case KeyEvent.KEY_RELEASED:
                  keyListener.keyReleased(e);
                  break;
            }
        }
        if (!e.isConsumed() && id == KeyEvent.KEY_PRESSED) {
            synchronized(listeners) {
                List<CellEditorListener> list = new ArrayList<CellEditorListener>(listeners);
                for (CellEditorListener listener : list) {
                    listener.editingStopped(new ChangeEvent(this));
                }
            }
        }
        e.consume();
    } else {
        super.processKeyEvent(e);
    }
}
 
Example 14
Source File: DetailsPanel.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
public void keyPressed(KeyEvent e) {
    tableKeyStroke = KeyStroke.getKeyStrokeForEvent(e);
}
 
Example 15
Source File: DetailsPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void keyPressed(KeyEvent e) {
    tableKeyStroke = KeyStroke.getKeyStrokeForEvent(e);
}
 
Example 16
Source File: MindMapDocumentEditor.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void onNonConsumedKeyEvent(@Nonnull final MindMapPanel source, @Nonnull final KeyEvent e, @Nonnull final KeyEventType type) {
  if (type == KeyEventType.PRESSED) {
    if (e.getModifiers() == 0) {
      switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
        case KeyEvent.VK_LEFT:
        case KeyEvent.VK_RIGHT:
        case KeyEvent.VK_DOWN: {
          e.consume();
        }
        break;
      }
    }
  }

  boolean activated = false;
  final ShortcutSet findAtMindMap = getFindAtMindMapShortcutSet();
  if (findAtMindMap != null) {
    final KeyStroke eventStroke = KeyStroke.getKeyStrokeForEvent(e);
    for (final Shortcut c : findAtMindMap.getShortcuts()) {
      if (c instanceof KeyboardShortcut) {
        final KeyboardShortcut keyboardShortcut = (KeyboardShortcut) c;
        final KeyStroke firstKeyStroke = keyboardShortcut.getFirstKeyStroke();
        final KeyStroke secondKeyStroke = keyboardShortcut.getSecondKeyStroke();

        if (firstKeyStroke != null && firstKeyStroke.getModifiers() == eventStroke.getModifiers() && firstKeyStroke.getKeyCode() == eventStroke.getKeyCode() && firstKeyStroke.getKeyChar() == eventStroke.getKeyChar()) {
          activated = true;
          break;
        }
        if (secondKeyStroke != null && secondKeyStroke.getModifiers() == eventStroke.getModifiers() && secondKeyStroke.getKeyCode() == eventStroke.getKeyCode() && secondKeyStroke.getKeyChar() == eventStroke.getKeyChar()) {
          activated = true;
          break;
        }
      }
    }
  }

  if (activated) {
    e.consume();
    activateTextSearchPanel();
  }

  if (!e.isConsumed() && e.getModifiers() == 0 && e.getKeyCode() == KeyEvent.VK_ESCAPE) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        findTextPanel.deactivate();
      }
    });
  }
}
 
Example 17
Source File: AutoHidingMenuBar.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void setAutoHideEnabled(boolean autoHideEnabled) {
    if (this.autoHideEnabled == autoHideEnabled)
        return;
    if (autoHideEnabled && Utilities.isMac())
        throw new UnsupportedOperationException("AutoHidingMenuBar not needed on MacOS");
    delayedAppearanceTimer.stop();
    if (autoHideEnabled) {
        menuBar = frame.getJMenuBar();
        if (menuBar == null)
            return;
    }
    this.autoHideEnabled = autoHideEnabled;
    final AWTEventListener awtEventListener = new AWTEventListener() {
        @Override
        public void eventDispatched(AWTEvent evt) {
            if (evt instanceof MouseEvent) {
                updateMenuBarVisibility((MouseEvent) evt);
            } else if (evt instanceof KeyEvent && !menuBar.isVisible()) {
                final KeyEvent keyEvent = (KeyEvent) evt;
                final KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(keyEvent);
                if (keyStroke != null && menuOpenKeyboardShortcuts.get(keyStroke) != null) {
                    setMenuBarVisible(true);
                    /* Make sure the menu bar is correctly sized and positioned before
                    processing keystrokes that might open a menu. */
                    frame.validate();
                    MenuSelectionManager.defaultManager().processKeyEvent(keyEvent);
                }
            }
        }
    };
    final ChangeListener menuSelectionListener = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            // This includes the case where the menu is closed after an item was selected.
            updateMenuBarVisibility(null);
        }
    };
    if (autoHideEnabled) {
        /* Use an AWTEventListener rather than a MouseMotionListener to be able to detect mouse
        motion even over components that would otherwise consume mouse motion events by
        themselves. */
        Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener,
                AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK);
        MenuSelectionManager.defaultManager().addChangeListener(menuSelectionListener);
    } else {
        Toolkit.getDefaultToolkit().removeAWTEventListener(awtEventListener);
        MenuSelectionManager.defaultManager().removeChangeListener(menuSelectionListener);
    }
    updateMenuBarVisibility(null);
}
 
Example 18
Source File: MacroDialogSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent evt, JTextComponent target) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("actionCommand='" + evt.getActionCommand() //NOI18N
                + "', modifiers=" + evt.getModifiers() //NOI18N
                + ", when=" + evt.getWhen() //NOI18N
                + ", paramString='" + evt.paramString() + "'"); //NOI18N
    }
    
    if (target == null) {
        return;
    }

    BaseKit kit = Utilities.getKit(target);
    if (kit == null) {
        return;
    }

    BaseDocument doc = Utilities.getDocument(target);
    if (doc == null) {
        return;
    }

    // changed as reponse to #250157: other events may get fired during
    // the course of key binding processing and if an event is processed
    // as nested (i.e. hierarchy change resulting from a component retracting from the screen),
    // thie following test would fail.
    AWTEvent maybeKeyEvent = EventQueue.getCurrentEvent();
    KeyStroke keyStroke = null;
    
    if (maybeKeyEvent instanceof KeyEvent) {
        keyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent) maybeKeyEvent);
    }

    // try simple keystorkes first
    MimePath mimeType = MimePath.parse(NbEditorUtilities.getMimeType(target));
    MacroDescription macro = null;
    if (keyStroke != null) {
        macro = findMacro(mimeType, keyStroke);
    } else {
        LOG.warning("KeyStroke could not be created for event " + maybeKeyEvent);
    }
    if (macro == null) {
        // if not found, try action command, which should contain complete multi keystroke
        KeyStroke[] shortcut = KeyStrokeUtils.getKeyStrokes(evt.getActionCommand());
        if (shortcut != null) {
            macro = findMacro(mimeType, shortcut);
        } else {
            LOG.warning("KeyStroke could not be created for action command " + evt.getActionCommand());
        }
    }

    if (macro == null) {
        error(target, "macro-not-found", KeyStrokeUtils.getKeyStrokeAsText(keyStroke)); // NOI18N
        return;
    }

    if (!runningActions.add(macro.getName())) { // this macro is already running, beware of loops
        error(target, "macro-loop", macro.getName()); // NOI18N
        return;
    }
    try {
        runMacro(target, doc, kit, macro);
    } finally {
        runningActions.remove(macro.getName());
    }
}
 
Example 19
Source File: RemoveSurroundingCodePanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void listKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listKeyReleased
    KeyStroke ks = KeyStroke.getKeyStrokeForEvent(evt);
    if (ks.getKeyCode() == KeyEvent.VK_ENTER || ks.getKeyCode() == KeyEvent.VK_SPACE) {
        invokeSelected();
    }
}
 
Example 20
Source File: DetailsPanel.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
public void keyPressed(KeyEvent e) {
    tableKeyStroke = KeyStroke.getKeyStrokeForEvent(e);
}