Java Code Examples for java.awt.event.KeyEvent#getModifiers()

The following examples show how to use java.awt.event.KeyEvent#getModifiers() . 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: MenuBar.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
boolean handleShortcut(KeyEvent e) {
    // Is it a key event?
    int id = e.getID();
    if (id != KeyEvent.KEY_PRESSED && id != KeyEvent.KEY_RELEASED) {
        return false;
    }

    // Is the accelerator modifier key pressed?
    int accelKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    if ((e.getModifiers() & accelKey) == 0) {
        return false;
    }

    // Pass MenuShortcut on to child menus.
    int nmenus = getMenuCount();
    for (int i = 0 ; i < nmenus ; i++) {
        Menu m = getMenu(i);
        if (m.handleShortcut(e)) {
            return true;
        }
    }
    return false;
}
 
Example 2
Source File: ModifierRobotEnhancedKeyTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void keyPressed(KeyEvent event) {

        tempPress = true;
        synchronized (tempLock) { tempLock.notifyAll(); }

        if (! startTest) {
            return;
        }
        for (int x = 0; x < inputMasks.length; x++) {
            if ((event.getModifiers() & inputMasks[x]) != 0) {
                System.out.println("Modifier set: " + event.getKeyModifiersText(inputMasks[x]));
                modifierStatus[x] = true;
            }
        }
        for (int x = 0; x < textKeys.length; x++) {
            if (event.getKeyCode() == textKeys[x]) {
                System.out.println("Text set: " + event.getKeyText(textKeys[x]));
                textStatus[x] = true;
            }
        }

        synchronized (keyLock) { keyLock.notifyAll(); }
    }
 
Example 3
Source File: JPACompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
    public void processKeyEvent(KeyEvent evt) {
        if (evt.getID() == KeyEvent.KEY_TYPED) {
            Completion completion = Completion.get();
            switch (evt.getKeyChar()) {
                case ' ':
                    if (evt.getModifiers() == 0) {
                        completion.hideCompletion();
                        completion.hideDocumentation();
                    }
                    break;
//                case ';': //TODO, can special handling be added even if we press these buttons within a literal?
//                case ',':
//                case '(':
//                    completion.hideCompletion();
//                    completion.hideDocumentation();
//                case '.':
//                    if (defaultAction((JTextComponent) evt.getSource(), Character.toString(evt.getKeyChar()))) {
//                        evt.consume();
//                        break;
//                    }
            }
        }
    }
 
Example 4
Source File: JavaTypeCompletionItem.java    From nb-springboot with Apache License 2.0 6 votes vote down vote up
@Override
public void processKeyEvent(KeyEvent evt) {
    if (evt.getID() == KeyEvent.KEY_TYPED && evt.getKeyChar() == '.' && elementKind == ElementKind.PACKAGE) {
        logger.log(Level.FINER, "Accepting package ''{0}'' and continuing completion", name);
        Completion.get().hideDocumentation();
        Completion.get().hideCompletion();
        JTextComponent tc = (JTextComponent) evt.getSource();
        BaseDocument doc = (BaseDocument) tc.getDocument();
        doc.runAtomic(new Runnable() {
            @Override
            public void run() {
                try {
                    doc.remove(dotOffset, caretOffset - dotOffset);
                    doc.insertString(dotOffset, name.concat("."), null);
                } catch (BadLocationException ble) {
                    //ignore
                }
            }
        });
        Completion.get().showCompletion();
        evt.consume();
    }
    // detect if Ctrl + Enter is pressed
    overwrite = evt.getKeyCode() == KeyEvent.VK_ENTER && (evt.getModifiers() & KeyEvent.CTRL_MASK) != 0;
}
 
Example 5
Source File: KeyboardPopupSwitcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void eventDispatched(AWTEvent event) {
    if (!(event instanceof KeyEvent)) {
        return;
    }
    KeyEvent keyEvent = (KeyEvent)event;
    if (keyEvent.getKeyCode() == KeyEvent.VK_ALT) {
        Toolkit.getDefaultToolkit().removeAWTEventListener(this);
        KeyEvent kev = new KeyEvent(
            (Component)keyEvent.getSource(), KeyEvent.KEY_RELEASED, keyEvent.getWhen(),
            keyEvent.getModifiers(), keyEvent.getKeyCode(), keyEvent.getKeyChar()

        );
        KeyboardPopupSwitcher.processInterruption(kev);
    }
}
 
Example 6
Source File: FocusComponentOnHotKey.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean postProcessKeyEvent(KeyEvent e) {
  if (e.getID() == KeyEvent.KEY_PRESSED) {
    if (e.getKeyCode() == keyCode && modifiers == e.getModifiers()) {
      component.requestFocus();
      return true;
    }
  }

  return false;
}
 
Example 7
Source File: XButtonPeer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void handleJavaKeyEvent(KeyEvent e) {
    int id = e.getID();
    switch (id) {
      case KeyEvent.KEY_PRESSED:
          if (e.getKeyCode() == KeyEvent.VK_SPACE)
          {
              pressed=true;
              armed=true;
              repaint();
              @SuppressWarnings("deprecation")
              final int modifiers = e.getModifiers();
              action(e.getWhen(), modifiers);
          }

          break;

      case KeyEvent.KEY_RELEASED:
          if (e.getKeyCode() == KeyEvent.VK_SPACE)
          {
              pressed = false;
              armed = false;
              repaint();
          }

          break;


    }
}
 
Example 8
Source File: HTMLTextArea.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void processKeyEvent(KeyEvent e) {
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_CONTEXT_MENU ||
       (code == KeyEvent.VK_F10 && e.getModifiers() == InputEvent.SHIFT_MASK)) {
        e.consume();
        showPopupMenu(null);
    }
    
    super.processKeyEvent(e);
}
 
Example 9
Source File: KeyboardTabSwitcher.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean postProcessKeyEvent(KeyEvent e) {
  if (e.getID() == KeyEvent.KEY_PRESSED && e.getModifiers() == InputEvent.CTRL_MASK) {
    if (e.getKeyCode() == KeyEvent.VK_PAGE_DOWN || e.getKeyCode() == KeyEvent.VK_LEFT) {
      goPrevPane();
      return true;
    } else if (e.getKeyCode() == KeyEvent.VK_PAGE_UP || e.getKeyCode() == KeyEvent.VK_RIGHT) {
      goNextPane();
      return true;
    }

  }
  return false;
}
 
Example 10
Source File: ChatRoomTransferDecorator.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void keyPressed(KeyEvent ke) {
       if (ke.getKeyCode() == KeyEvent.VK_V) {
           int i = ke.getModifiers();
           if ((i & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
               Clipboard clb = Toolkit.getDefaultToolkit().getSystemClipboard();
               Transferable contents = clb.getContents(ke.getSource());
               if (contents != null && contents.getTransferDataFlavors().length == 1) {
                   if (contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                       SparkManager.getTransferManager().sendImage(SparkTransferManager.getClipboard(), chatRoom);
                   }
               }
           }
       }
   }
 
Example 11
Source File: InstantRenamePerformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void keyPressed(KeyEvent e) {
if (   (e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0) 
           || (e.getKeyCode() == KeyEvent.VK_ENTER  && e.getModifiers() == 0)) {
    release();
    e.consume();
}
   }
 
Example 12
Source File: JDA.java    From java-disassembler with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isShiftDown(KeyEvent e) {
    return ((e.getModifiers() & KeyEvent.SHIFT_MASK) != 0);
}
 
Example 13
Source File: GuiBoard.java    From FancyBing with GNU General Public License v3.0 4 votes vote down vote up
private void keyPressed(KeyEvent event)
{
    int code = event.getKeyCode();
    int modifiers = event.getModifiers();
    if (code == KeyEvent.VK_ENTER)
    {
        int mask = (ActionEvent.CTRL_MASK
                    | ActionEvent.ALT_MASK
                    | ActionEvent.META_MASK);
        boolean modifiedSelect = ((modifiers & mask) != 0);
        if (getShowCursor() && m_cursor != null)
            fieldClicked(m_cursor, modifiedSelect);
        return;
    }
    if ((modifiers & ActionEvent.CTRL_MASK) != 0
        || ! getShowCursor() || m_cursor == null)
        return;
    boolean shiftModifier = ((modifiers & ActionEvent.SHIFT_MASK) != 0);
    GoPoint point = m_cursor;
    if (code == KeyEvent.VK_DOWN)
    {
        point = point.down();
        if (shiftModifier)
            while (! isHandicapLineOrEdge(point.getY()))
                point = point.down();
    }
    else if (code == KeyEvent.VK_UP)
    {
        point = point.up(m_size);
        if (shiftModifier)
            while (! isHandicapLineOrEdge(point.getY()))
                point = point.up(m_size);
    }
    else if (code == KeyEvent.VK_LEFT)
    {
        point = point.left();
        if (shiftModifier)
            while (! isHandicapLineOrEdge(point.getX()))
                point = point.left();
    }
    else if (code == KeyEvent.VK_RIGHT)
    {
        point = point.right(m_size);
        if (shiftModifier)
            while (! isHandicapLineOrEdge(point.getX()))
                point = point.right(m_size);
    }
    setCursor(point);
}
 
Example 14
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 15
Source File: CDefaultLabelEventHandler.java    From binnavi with Apache License 2.0 4 votes vote down vote up
@Override
public void keyPressed(final KeyEvent event) {
  if (!isActive()) {
    return;
  }

  if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
    deactivateLabelContent();

    return;
  }

  if ((event.getKeyCode() == KeyEvent.VK_TAB) && (event.getModifiers() != 0)
      && (event.getModifiers() != InputEvent.SHIFT_DOWN_MASK)) {
    return;
  }

  if (!getActiveLabelContent().isSelectable()) {
    return;
  }

  CAbstractKeyBehavior behaviour = null;

  final char keyText = KeyEvent.getKeyText(event.getKeyCode()).charAt(0);

  if (event.isControlDown() && (keyText >= 'A') && (keyText <= 'Z')) {
    behaviour = m_ctrlKeyBehaviourMap.get(event.getKeyCode());
  }

  if (behaviour == null) {
    behaviour = m_keyBehaviourMap.get(event.getKeyCode());

    if ((behaviour == null) && (event.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
        && !event.isControlDown() && getActiveLabelContent().isEditable()) {
      behaviour = m_keyBehaviourMap.get(null);
    }
  }

  if (behaviour != null) {
    int y = -1;
    String oldContent = "";

    if (getActiveLabelContent().isEditable()) {
      y = getActiveLabelContent().getCaret().getYmouseReleased();
      oldContent = getContentSnippet(y);
    }

    behaviour.keyPressed(getActiveLabelContent(), event);

    if (y > -1) {
      final String newContent = getContentSnippet(y);

      if (!oldContent.equals(newContent) && !oldContent.isEmpty()) {
        for (final ILabelEditableContentListener listener : m_editModeListener) {
          listener.editableContentChanged(getActiveLabelContent());
        }
      }
    }

    m_activeRealizer.regenerate();

    m_activeRealizer.repaint();

    m_graph.updateViews();
  }

  event.consume();
}
 
Example 16
Source File: BaseTable.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Overridden to allow standard keybinding processing of VK_TAB and
 * abort any pending drag operation on the vertical grid. */
public void processKeyEvent(KeyEvent e) {
    if (dragListener.isArmed()) {
        dragListener.setArmed(false);
    }

    boolean suppressDefaultHandling = ((searchField != null) && searchField.isShowing()) &&
        ((e.getKeyCode() == KeyEvent.VK_UP) || (e.getKeyCode() == KeyEvent.VK_DOWN));

    //Manually hook in the bindings for tab - does not seem to get called
    //automatically
    if (e.getKeyCode() != KeyEvent.VK_TAB) {
        if (!suppressDefaultHandling) {
            //Either the search field or the table should handle up/down, not both
            super.processKeyEvent(e);
        }

        if (!e.isConsumed()) {
            if ((e.getID() == KeyEvent.KEY_PRESSED) && !isEditing()) {
                int modifiers = e.getModifiers();
                int keyCode = e.getKeyCode();

                if (((modifiers > 0) && (modifiers != KeyEvent.SHIFT_MASK)) || e.isActionKey()) {
                    return;
                }

                char c = e.getKeyChar();

                if (!Character.isISOControl(c) && (keyCode != KeyEvent.VK_SHIFT) &&
                        (keyCode != KeyEvent.VK_ESCAPE)) {
                    searchArmed = true;
                    e.consume();
                }
            } else if (searchArmed && (e.getID() == KeyEvent.KEY_TYPED)) {
                passToSearchField(e);
                e.consume();
                searchArmed = false;
            } else {
                searchArmed = false;
            }
        }
    } else {
        processKeyBinding(
            KeyStroke.getKeyStroke(e.VK_TAB, e.getModifiersEx(), e.getID() == e.KEY_RELEASED), e,
            JComponent.WHEN_FOCUSED, e.getID() == e.KEY_PRESSED
        );
    }
}
 
Example 17
Source File: KeyCompletionItem.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
@Override
public void processKeyEvent(KeyEvent evt) {
    // detect if Ctrl + Enter is pressed
    overwrite = evt.getKeyCode() == KeyEvent.VK_ENTER && (evt.getModifiers() & KeyEvent.CTRL_MASK) != 0;
}
 
Example 18
Source File: IdeKeyEventDispatcher.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean inInitState() {
  Component focusOwner = myContext.getFocusOwner();
  boolean isModalContext = myContext.isModalContext();
  DataContext dataContext = myContext.getDataContext();
  KeyEvent e = myContext.getInputEvent();

  // http://www.jetbrains.net/jira/browse/IDEADEV-12372
  if (myLeftCtrlPressed && myRightAltPressed && focusOwner != null && e.getModifiers() == (InputEvent.CTRL_MASK | InputEvent.ALT_MASK)) {
    if (Registry.is("actionSystem.force.alt.gr")) {
      return false;
    }
    final InputContext inputContext = focusOwner.getInputContext();
    if (inputContext != null) {
      Locale locale = inputContext.getLocale();
      if (locale != null) {
        @NonNls final String language = locale.getLanguage();
        if (ALT_GR_LAYOUTS.contains(language)) {
          // don't search for shortcuts
          return false;
        }
      }
    }
  }

  KeyStroke originalKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(e);
  if (originalKeyStroke == null) {
    return false;
  }
  KeyStroke keyStroke = getKeyStrokeWithoutMouseModifiers(originalKeyStroke);

  if (myKeyGestureProcessor.processInitState()) {
    return true;
  }

  if (SystemInfo.isMac) {
    boolean keyTyped = e.getID() == KeyEvent.KEY_TYPED;
    boolean hasMnemonicsInWindow = e.getID() == KeyEvent.KEY_PRESSED && hasMnemonicInWindow(focusOwner, e.getKeyCode()) || keyTyped && hasMnemonicInWindow(focusOwner, e.getKeyChar());
    boolean imEnabled = IdeEventQueue.getInstance().isInputMethodEnabled();

    if (e.getModifiersEx() == InputEvent.ALT_DOWN_MASK && (hasMnemonicsInWindow || !imEnabled && keyTyped)) {
      setPressedWasProcessed(true);
      setState(KeyState.STATE_PROCESSED);
      return false;
    }
  }

  updateCurrentContext(focusOwner, new KeyboardShortcut(keyStroke, null), isModalContext);
  if (myContext.getActions().isEmpty()) {
    // there's nothing mapped for this stroke
    return false;
  }

  if (myContext.isHasSecondStroke()) {
    myFirstKeyStroke = keyStroke;
    final ArrayList<Pair<AnAction, KeyStroke>> secondKeyStrokes = getSecondKeystrokeActions();

    final Project project = dataContext.getData(CommonDataKeys.PROJECT);
    StringBuilder message = new StringBuilder();
    message.append(KeyMapBundle.message("prefix.key.pressed.message"));
    message.append(' ');
    for (int i = 0; i < secondKeyStrokes.size(); i++) {
      Pair<AnAction, KeyStroke> pair = secondKeyStrokes.get(i);
      if (i > 0) message.append(", ");
      message.append(pair.getFirst().getTemplatePresentation().getText());
      message.append(" (");
      message.append(KeymapUtil.getKeystrokeText(pair.getSecond()));
      message.append(")");
    }

    StatusBar.Info.set(message.toString(), project);

    mySecondStrokeTimeout.cancelAllRequests();
    mySecondStrokeTimeout.addRequest(mySecondStrokeTimeoutRunnable, Registry.intValue("actionSystem.secondKeystrokeTimeout"));

    if (Registry.is("actionSystem.secondKeystrokeAutoPopupEnabled")) {
      mySecondKeystrokePopupTimeout.cancelAllRequests();
      if (secondKeyStrokes.size() > 1) {
        final DataContext oldContext = myContext.getDataContext();
        mySecondKeystrokePopupTimeout.addRequest(() -> {
          if (myState == KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE) {
            StatusBar.Info.set(null, oldContext.getData(CommonDataKeys.PROJECT));
            new SecondaryKeystrokePopup(myFirstKeyStroke, secondKeyStrokes, oldContext).showInBestPositionFor(oldContext);
          }
        }, Registry.intValue("actionSystem.secondKeystrokePopupTimeout"));
      }
    }

    setState(KeyState.STATE_WAIT_FOR_SECOND_KEYSTROKE);
    return true;
  }
  else {
    return processAction(e, myActionProcessor);
  }
}
 
Example 19
Source File: MBasicTable.java    From javamelody with Apache License 2.0 4 votes vote down vote up
/**
 * Gestion des événements clavier sur cette table.
 *
 * @param event
 *           KeyEvent
 */
protected void keyPressed(final KeyEvent event) {
	final int keyCode = event.getKeyCode();
	final int modifiers = event.getModifiers();
	if ((modifiers & Event.CTRL_MASK) != 0 && keyCode == KeyEvent.VK_ADD) {
		adjustColumnWidths();
	}
	// else if (modifiers == 0)
	// {
	// final int selectedColumn = getSelectedColumn() != -1 ? getSelectedColumn() : 0;
	// final int selectedRow = getSelectedRow() != -1 ? getSelectedRow() : 0;
	// final int rowCount = getRowCount();
	// if (isCellEditable(selectedRow, selectedColumn) || rowCount == 0)
	// {
	// return;
	// }
	// final String keyChar = String.valueOf(event.getKeyChar());
	// String text;
	// for (int i = selectedRow + 1; i < rowCount; i++)
	// {
	// text = getTextAt(i, selectedColumn);
	// if (text != null && text.regionMatches(true, 0, keyChar, 0, 1))
	// {
	// setRowSelectionInterval(i, i);
	// setColumnSelectionInterval(selectedColumn, selectedColumn);
	// scrollRectToVisible(getCellRect(i, selectedColumn, true));
	// return;
	// }
	// }
	// for (int i = 0; i <= selectedRow; i++)
	// {
	// text = getTextAt(i, selectedColumn);
	// if (text != null && text.regionMatches(true, 0, keyChar, 0, 1))
	// {
	// setRowSelectionInterval(i, i);
	// setColumnSelectionInterval(selectedColumn, selectedColumn);
	// scrollRectToVisible(getCellRect(i, selectedColumn, true));
	// return;
	// }
	// }
	// }
}
 
Example 20
Source File: ValueCompletionItem.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
@Override
public void processKeyEvent(KeyEvent evt) {
    // detect if Ctrl + Enter is pressed
    overwrite = evt.getKeyCode() == KeyEvent.VK_ENTER && (evt.getModifiers() & KeyEvent.CTRL_MASK) != 0;
}