Example usage for java.awt.event KeyEvent getModifiers

List of usage examples for java.awt.event KeyEvent getModifiers

Introduction

In this page you can find the example usage for java.awt.event KeyEvent getModifiers.

Prototype

@Deprecated(since = "9")
public int getModifiers() 

Source Link

Document

Returns the modifier mask for this event.

Usage

From source file:com.github.fritaly.dualcommander.DualCommander.java

@Override
public void keyReleased(KeyEvent e) {
    if ((e.getModifiers() | KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK) {
        shiftPressed = false;//from ww  w.  j  ava 2  s  .  co  m

        if (logger.isDebugEnabled()) {
            logger.debug("[Shift] key released");
        }
    }
    if ((e.getModifiers() | KeyEvent.META_DOWN_MASK) == KeyEvent.META_DOWN_MASK) {
        metaPressed = false;

        if (logger.isDebugEnabled()) {
            logger.debug("[Meta] key released");
        }
    }
}

From source file:com.github.fritaly.dualcommander.DirectoryBrowser.java

@Override
public void keyReleased(KeyEvent e) {
    if (e.getSource() != table) {
        return;//from   ww w .java2 s.  co m
    }

    // Propagate event to our listeners
    processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(),
            e.getKeyLocation()));
}

From source file:com.github.fritaly.dualcommander.DirectoryBrowser.java

@Override
public void keyTyped(KeyEvent e) {
    if (e.getSource() != table) {
        return;//from www  .j  av a 2 s  .  com
    }

    // Propagate event to our listeners
    processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), e.getKeyChar(),
            e.getKeyLocation()));
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;/*ww  w .  j a va2s  . c o m*/
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    //System.out.println(cp-toSetIn.length()+" - "+cp);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    //System.out.println("Added char: '"+toSetIn+"'");
                    //System.out.println("LastBeginning: '"+lastBeginning+"'");

                    lastCompletions = findCompletions(lastBeginning, comp);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.length; i++) {
                        String lastCompletion = lastCompletions[i];
                        //System.out.println("Completion["+i+"] = "+lastCompletion);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    //System.out.println("Index now: "+lastShownCompletion);
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

                LOGGER.debug("discont toSetIn: >" + toSetIn + "'<' lastBeginning: >" + lastBeginning + '<');

                String[] completed = findCompletions(lastBeginning, comp);
                if ((completed != null) && (completed.length > 0)) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed[0];
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //Util.pr(""+lastLen);
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);
            if (currentword == null) {
                currentword = new StringBuffer();
            }

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters 
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

From source file:net.sf.jabref.gui.MainTableSelectionListener.java

/**
 * Receive key event on the main table. If the key is a letter or a digit,
 * we should select the first entry in the table which starts with the given
 * letter in the column by which the table is sorted.
 * @param e The KeyEvent// w w w .  j  a  v  a2  s  . c o  m
 */
@Override
public void keyTyped(KeyEvent e) {
    if ((!e.isActionKey()) && Character.isLetterOrDigit(e.getKeyChar())
    //&& !e.isControlDown() && !e.isAltDown() && !e.isMetaDown()) {
            && (e.getModifiers() == 0)) {
        long time = System.currentTimeMillis();
        long QUICK_JUMP_TIMEOUT = 2000;
        if ((time - lastPressedTime) > QUICK_JUMP_TIMEOUT) {
            lastPressedCount = 0; // Reset last pressed character
        }
        // Update timestamp:
        lastPressedTime = time;
        // Add the new char to the search array:
        int c = e.getKeyChar();
        if (lastPressedCount < lastPressed.length) {
            lastPressed[lastPressedCount] = c;
            lastPressedCount++;
        }

        int sortingColumn = table.getSortingColumn(0);
        if (sortingColumn == -1) {
            return; // No sorting? TODO: look up by author, etc.?
        }
        // TODO: the following lookup should be done by a faster algorithm,
        // such as binary search. But the table may not be sorted properly,
        // due to marked entries, search etc., which rules out the binary search.
        int startRow = 0;
        /*if ((c == lastPressed) && (lastQuickJumpRow >= 0)) {
        if (lastQuickJumpRow < table.getRowCount()-1)
            startRow = lastQuickJumpRow+1;
        }*/

        boolean done = false;
        while (!done) {
            for (int i = startRow; i < table.getRowCount(); i++) {
                Object o = table.getValueAt(i, sortingColumn);
                if (o == null) {
                    continue;
                }
                String s = o.toString().toLowerCase();
                if (s.length() >= lastPressedCount) {
                    for (int j = 0; j < lastPressedCount; j++) {
                        if (s.charAt(j) != lastPressed[j]) {
                            break; // Escape the loop immediately when we find a mismatch
                        } else if (j == (lastPressedCount - 1)) {
                            // We found a match:
                            table.setRowSelectionInterval(i, i);
                            table.ensureVisible(i);
                            return;
                        }
                    }
                    //if ((s.length() >= 1) && (s.charAt(0) == c)) {
                    //}
                }
            }
            // Finished, no result. If we didn't start at the beginning of
            // the table, try that. Otherwise, exit the while loop.
            if (startRow > 0) {
                startRow = 0;
            } else {
                done = true;
            }

        }

    } else if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
        lastPressedCount = 0;

    }
}

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;/*from   w w  w.  java  2  s  .c  o m*/
    }

    // don't do auto completion inside words
    if (!atEndOfWord((JTextComponent) e.getSource())) {
        return;
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    lastCompletions = findCompletions(lastBeginning);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.size(); i++) {
                        String lastCompletion = lastCompletions.get(i);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

                LOGGER.debug("discont toSetIn: >" + toSetIn + "'<' lastBeginning: >" + lastBeginning + '<');

                List<String> completed = findCompletions(lastBeginning);
                if ((completed != null) && (!completed.isEmpty())) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed.get(0);
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

From source file:com.github.fritaly.dualcommander.TabbedPane.java

@Override
public void keyPressed(KeyEvent e) {
    if (e.getSource() == getSelectedComponent()) {
        final boolean metaDown = (e.getModifiersEx() | KeyEvent.META_DOWN_MASK) == KeyEvent.META_DOWN_MASK;

        if ((e.getKeyCode() == KeyEvent.VK_T) && metaDown) {
            // Create a new tab and set to focus on it
            setSelectedComponent(addBrowserTab(getActiveBrowser().getDirectory()));
        } else if ((e.getKeyCode() == KeyEvent.VK_W) && metaDown) {
            if (getTabCount() > 1) {
                // Close the current tab (only if not the last one)
                closeActiveBrowserTab();
            }//from  w  ww. j a v  a2 s. c  om
        } else if ((e.getKeyCode() >= KeyEvent.VK_1) && (e.getKeyCode() <= KeyEvent.VK_9) && metaDown) {
            final int index = e.getKeyCode() - KeyEvent.VK_1;

            if (index <= getTabCount() - 1) {
                setSelectedIndex(index);
            }
        } else {
            // Propagate event to our listeners
            processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(),
                    e.getKeyChar(), e.getKeyLocation()));
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.validation.ValFormattedTextField.java

/**
 * @param e the key event//from  w  ww.j a  v  a  2 s.com
 */
protected void checkForPaste(final KeyEvent e) {
    if (e.getKeyCode() == pasteKeyStroke.getKeyCode() && e.getModifiers() == pasteKeyStroke.getModifiers()) {
        String text = UIHelper.getTextFromClipboard();
        if (text != null && text.length() <= formatter.getLength()) {
            setValue(text, null);
        }
    }
}

From source file:com.projity.pm.graphic.spreadsheet.SpreadSheet.java

protected void initListeners() {
    addKeyListener(new KeyAdapter() { // TODO need to fix focus problems elsewhere for this to always work
        public void keyPressed(KeyEvent e) {
            int row = getSelectedRow();
            if (row < 0)
                return;
            CommonSpreadSheetModel model = (CommonSpreadSheetModel) getModel();
            if (e.getKeyCode() == KeyEvent.VK_INSERT)
                executeAction(MenuActionConstants.ACTION_NEW);
            else if (e.getKeyCode() == KeyEvent.VK_DELETE)
                executeAction(MenuActionConstants.ACTION_DELETE);
            else if (e.getKeyCode() == KeyEvent.VK_F3)
                GraphicManager.getInstance().doFind(SpreadSheet.this, null);
            else if (e.getKeyCode() == KeyEvent.VK_F && e.getModifiers() == KeyEvent.CTRL_MASK)
                GraphicManager.getInstance().doFind(SpreadSheet.this, null);

        }//from ww w .  jav  a2s. com
    });

}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code>
 * method, when CTRL+R is pressed invokes the
 * <code>ChatWritePanel.redo()</code> method.
 *
 * @param e the <tt>KeyEvent</tt> that notified us
 *///w  ww . j  a v a  2 s  .com
public void keyPressed(KeyEvent e) {
    if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z)
    // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canUndo())
            undo();
    } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK
            && (e.getKeyCode() == KeyEvent.VK_R)
            // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canRedo())
            redo();
    } else if (e.getKeyCode() == KeyEvent.VK_TAB) {
        if (!(chatPanel.getChatSession() instanceof ConferenceChatSession))
            return;

        e.consume();
        int index = ((JEditorPane) e.getSource()).getCaretPosition();

        StringBuffer message = new StringBuffer(chatPanel.getMessage());

        int position = index - 1;

        while (position > 0 && (message.charAt(position) != ' ')) {
            position--;
        }

        if (position != 0)
            position++;

        String sequence = message.substring(position, index);

        if (sequence.length() <= 0) {
            // Do not look for matching contacts if the matching pattern is
            // 0 chars long, since all contacts will match.
            return;
        }

        Iterator<ChatContact<?>> iter = chatPanel.getChatSession().getParticipants();
        ArrayList<String> contacts = new ArrayList<String>();
        while (iter.hasNext()) {
            ChatContact<?> c = iter.next();
            if (c.getName().length() >= (index - position)
                    && c.getName().substring(0, index - position).equals(sequence)) {
                message.replace(position, index, c.getName().substring(0, index - position));
                contacts.add(c.getName());
            }
        }

        if (contacts.size() > 1) {
            char key = contacts.get(0).charAt(index - position - 1);
            int pos = index - position - 1;
            boolean flag = true;

            while (flag) {
                try {
                    for (String name : contacts) {
                        if (key != name.charAt(pos)) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        pos++;
                        key = contacts.get(0).charAt(pos);
                    }
                } catch (IndexOutOfBoundsException exp) {
                    flag = false;
                }
            }

            message.replace(position, index, contacts.get(0).substring(0, pos));

            Iterator<String> contactIter = contacts.iterator();
            String contactList = "<DIV align='left'><h5>";
            while (contactIter.hasNext()) {
                contactList += contactIter.next() + " ";
            }
            contactList += "</h5></DIV>";

            chatPanel.getChatConversationPanel().appendMessageToEnd(contactList,
                    ChatHtmlUtils.HTML_CONTENT_TYPE);
        } else if (contacts.size() == 1) {
            String limiter = (position == 0) ? ": " : "";
            message.replace(position, index, contacts.get(0) + limiter);
        }

        try {
            ((JEditorPane) e.getSource()).getDocument().remove(0,
                    ((JEditorPane) e.getSource()).getDocument().getLength());
            ((JEditorPane) e.getSource()).getDocument().insertString(0, message.toString(), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
        // Only enters editing mode if the write panel is empty in
        // order not to lose the current message contents, if any.
        if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) {
            this.chatPanel.startLastMessageCorrection();
            e.consume();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        if (chatPanel.isMessageCorrectionActive()) {
            Document doc = editorPane.getDocument();
            if (editorPane.getCaretPosition() == doc.getLength()) {
                chatPanel.stopMessageCorrection();
            }
        }
    }
}