Example usage for java.awt.event KeyEvent VK_SHIFT

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

Introduction

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

Prototype

int VK_SHIFT

To view the source code for java.awt.event KeyEvent VK_SHIFT.

Click Source Link

Document

Constant for the SHIFT virtual key.

Usage

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

@Override
public void keyPressed(KeyEvent e) {
    if ((toSetIn != null) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
        JTextComponent comp = (JTextComponent) e.getSource();

        // replace typed characters by characters from completion
        lastBeginning = lastCompletions.get(lastShownCompletion);

        int end = comp.getSelectionEnd();
        comp.select(end, end);/*from   w ww.  java  2  s .  co m*/
        toSetIn = null;
        if (consumeEnterKey) {
            e.consume();
        }
    }
    // Cycle through alternative completions when user presses PGUP/PGDN:
    else if ((e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), 1);
        e.consume();
    } else if ((e.getKeyCode() == KeyEvent.VK_PAGE_UP) && (toSetIn != null)) {
        cycle((JTextComponent) e.getSource(), -1);
        e.consume();
    }
    //        else if ((e.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
    //           StringBuffer currentword = getCurrentWord((JTextComponent) e.getSource());
    //           // delete last char to obey semantics of back space
    //           currentword.deleteCharAt(currentword.length()-1);
    //           doCompletion(currentword, e);
    //        }
    else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED) {
        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            // shift is OK, everything else leads to a reset
            LOGGER.debug("Special case: shift pressed. No action.");
        } else {
            resetAutoCompletion();
        }
    } else {
        LOGGER.debug("Special case: defined character, but not caught above");
    }
}

From source file:cz.babi.desktop.remoteme.common.Controller.java

/**
 * Make key stroke./*ww  w.  ja  v a2s.c o  m*/
 * @param character Key(s) to stroke.
 */
private void makeStroke(Integer[] keyCodes) {
    /*
     * There is a bug with shift and arrows.
     * Workaround is turn num lock off.
     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4908075
     */
    boolean needSetNumlockOn = false;
    /* If numlock is on. */
    if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_NUM_LOCK)) {
        boolean isShift = false;
        boolean isArrow = false;

        /* Check if there is a shift or an arrow. */
        for (Integer integer : keyCodes) {
            if (integer == KeyEvent.VK_SHIFT)
                isShift = true;
            if (integer == KeyEvent.VK_LEFT)
                isArrow = true;
            if (integer == KeyEvent.VK_RIGHT)
                isArrow = true;
            if (integer == KeyEvent.VK_UP)
                isArrow = true;
            if (integer == KeyEvent.VK_DOWN)
                isArrow = true;
        }

        /* Disable numlock. */
        if (isShift && isArrow) {
            robot.keyPress(KeyEvent.VK_NUM_LOCK);
            robot.keyRelease(KeyEvent.VK_NUM_LOCK);
            needSetNumlockOn = true;
        }
    }

    /* Do press. */
    for (int i = 0; i < keyCodes.length; i++) {
        if (Common.DEBUG)
            LOGGER.debug("[keyPress][" + keyCodes[i] + "]");

        robot.keyPress(keyCodes[i]);
    }

    /* Do release. */
    for (int i = keyCodes.length - 1; i >= 0; i--) {
        if (Common.DEBUG)
            LOGGER.debug("[keyRelease][" + keyCodes[i] + "]");

        robot.keyRelease(keyCodes[i]);
    }

    /* Set numlock back. */
    if (needSetNumlockOn) {
        robot.keyPress(KeyEvent.VK_NUM_LOCK);
        robot.keyRelease(KeyEvent.VK_NUM_LOCK);
    }
}

From source file:com.ubershy.streamsis.actions.HotkeyAction.java

/**
 * Presses the provided {@link KeyCodeCombination}'s keys.
 *
 * @param kb            the KeyCodeCombination
 * @return true, if successful/*from www .j a va 2 s  .  c  om*/
 */
@SuppressWarnings("deprecation")
protected boolean keysDown(KeyCodeCombination kb) {
    try {
        if (kb.getShortcut() == ModifierValue.DOWN) {
            robot.keyPress(shortcutKeyEvent);
            Thread.sleep(modifiersPressSleepTime);
        }
        if (kb.getAlt() == ModifierValue.DOWN) {
            robot.keyPress(KeyEvent.VK_ALT);
            Thread.sleep(modifiersPressSleepTime);
        }
        if (kb.getShift() == ModifierValue.DOWN) {
            robot.keyPress(KeyEvent.VK_SHIFT);
            Thread.sleep(modifiersPressSleepTime);
        }
        // I know this is a bad practice. Do you have any idea how to avoid this, stranger?
        robot.keyPress(kb.getCode().impl_getCode());
        Thread.sleep(modifiersPressSleepTime);
    } catch (InterruptedException e) {
        logger.debug("Haha, not this time, InterruptedException!");
        return false;
    }
    return true;
}

From source file:com.ubershy.streamsis.actions.HotkeyAction.java

/**
 * Releases the provided {@link KeyCodeCombination}'s keys.
 *
 * @param kb            the KeyCodeCombination
 * @return true, if successful/* ww  w. j  a v  a  2s . c o  m*/
 */
@SuppressWarnings("deprecation")
protected boolean keysUp(KeyCodeCombination kb) {
    try {
        // I know this is a bad practice. Do you have any idea how to avoid this, stranger?
        robot.keyRelease(kb.getCode().impl_getCode());
        Thread.sleep(modifiersPressSleepTime);
        if (kb.getShift() == ModifierValue.DOWN) {
            robot.keyRelease(KeyEvent.VK_SHIFT);
            Thread.sleep(modifiersPressSleepTime);
        }
        if (kb.getAlt() == ModifierValue.DOWN) {
            robot.keyRelease(KeyEvent.VK_ALT);
            Thread.sleep(modifiersPressSleepTime);
        }
        if (kb.getShortcut() == ModifierValue.DOWN) {
            robot.keyRelease(shortcutKeyEvent);
        }
    } catch (InterruptedException e) {
        logger.debug("Haha, not this time, InterruptedException!");
        return false;
    }
    return true;
}

From source file:org.eclipse.jubula.rc.common.driver.KeyTyper.java

/**
 * @param keyStroke KeyStroke whose modifiers are requested
 * @return a List of KeyCodes (hopefully) realising the ModifierMask contained in the KeyStroke
 *//*  www  . j  a  v  a2  s . com*/
private List modifierKeyCodes(KeyStroke keyStroke) {
    List l = new LinkedList();
    int modifiers = keyStroke.getModifiers();
    // this is jdk 1.3 - code.
    // use ALT_DOWN_MASK instead etc. with jdk 1.4 !
    if ((modifiers & InputEvent.ALT_MASK) != 0) {
        l.add(new Integer(KeyEvent.VK_ALT));
    }
    if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
        l.add(new Integer(KeyEvent.VK_ALT_GRAPH));
    }
    if ((modifiers & InputEvent.CTRL_MASK) != 0) {
        l.add(new Integer(KeyEvent.VK_CONTROL));
    }
    if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
        l.add(new Integer(KeyEvent.VK_SHIFT));
    }
    if ((modifiers & InputEvent.META_MASK) != 0) {
        l.add(new Integer(KeyEvent.VK_META));
    }
    return l;
}

From source file:com.fanniemae.ezpie.actions.HighlightScan.java

private void keyPressReleaseShiftTab(int delay) {
    this._robot.keyPress(KeyEvent.VK_SHIFT);
    this._robot.keyPress(KeyEvent.VK_TAB);
    sleep(delay);// ww  w. j a  v  a  2 s  .  co m
    this._robot.keyRelease(KeyEvent.VK_SHIFT);
    this._robot.keyRelease(KeyEvent.VK_TAB);
}

From source file:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
  * // w  ww.  j  a va2 s  . c  om
  */
protected void buildSpreadsheet() {

    this.setShowGrid(true);

    int numRows = model.getRowCount();

    scrollPane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    final SpreadSheet ss = this;
    JButton cornerBtn = UIHelper.createIconBtn("Blank", IconManager.IconSize.Std16, "SelectAll",
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    ss.selectAll();
                }
            });
    cornerBtn.setEnabled(true);
    scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, cornerBtn);

    // Allows row and collumn selections to exit at the same time
    setCellSelectionEnabled(true);

    setRowSelectionAllowed(true);
    setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    addMouseListener(new MouseAdapter() {
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
         */
        @SuppressWarnings("synthetic-access")
        @Override
        public void mouseReleased(MouseEvent e) {
            // XXX For Java 5 Bug
            prevRowSelInx = getSelectedRow();
            prevColSelInx = getSelectedColumn();

            if (e.getClickCount() == 2) {
                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                ss.editCellAt(rowIndexStart, colIndexStart);
                if (ss.getEditorComponent() != null && ss.getEditorComponent() instanceof JTextComponent) {
                    ss.getEditorComponent().requestFocus();

                    final JTextComponent txtComp = (JTextComponent) ss.getEditorComponent();
                    String txt = txtComp.getText();
                    FontMetrics fm = txtComp.getFontMetrics(txtComp.getFont());
                    int x = e.getPoint().x - ss.getEditorComponent().getBounds().x - 1;
                    int prevWidth = 0;
                    for (int i = 0; i < txt.length(); i++) {

                        int width = fm.stringWidth(txt.substring(0, i));
                        int basePlusHalf = prevWidth + (int) (((width - prevWidth) / 2) + 0.5);
                        //System.out.println(prevWidth + " X[" + x + "] " + width+" ["+txt.substring(0, i)+"] " + i + " " + basePlusHalf);
                        //System.out.println(" X[" + x + "] " + prevWidth + " - "+ basePlusHalf+" - " + width+" ["+txt.substring(0, i)+"] " + i);
                        if (x < width) {
                            // Clearing the selection is needed for Window for some reason
                            final int inx = i + (x <= basePlusHalf ? -1 : 0);
                            SwingUtilities.invokeLater(new Runnable() {
                                @SuppressWarnings("synthetic-access")
                                public void run() {
                                    txtComp.setSelectionStart(0);
                                    txtComp.setSelectionEnd(0);
                                    txtComp.setCaretPosition(inx > 0 ? inx : 0);
                                }
                            });
                            break;
                        }
                        prevWidth = width;
                    }
                }
            }
        }
    });

    // Create a row-header to display row numbers.
    // This row-header is made of labels whose Borders,
    // Foregrounds, Backgrounds, and Fonts must be
    // the one used for the table column headers.
    // Also ensure that the row-header labels and the table
    // rows have the same height.

    //i have no idea WHY this has to be called.  i rearranged
    //the table and find replace panel, 
    // i started getting an array index out of
    //bounds on the column header ON MAC ONLY.  
    //tried firing this off, first and it fixed the problem.//meg
    this.getModel().fireTableStructureChanged();

    /*
     * Create the Row Header Panel
     */
    rowHeaderPanel = new JPanel((LayoutManager) null);

    if (getColumnModel().getColumnCount() > 0) {
        TableColumn column = getColumnModel().getColumn(0);
        TableCellRenderer renderer = getTableHeader().getDefaultRenderer();
        if (renderer == null) {
            renderer = column.getHeaderRenderer();
        }

        Component cellRenderComp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false,
                false, -1, 0);
        cellFont = cellRenderComp.getFont();

    } else {
        cellFont = (new JLabel()).getFont();
    }

    // Calculate Row Height
    cellBorder = (Border) UIManager.getDefaults().get("TableHeader.cellBorder");
    Insets insets = cellBorder.getBorderInsets(tableHeader);
    FontMetrics metrics = getFontMetrics(cellFont);

    rowHeight = insets.bottom + metrics.getHeight() + insets.top;
    rowLabelWidth = metrics.stringWidth("9999") + insets.right + insets.left;

    Dimension dim = new Dimension(rowLabelWidth, rowHeight * numRows);
    rowHeaderPanel.setPreferredSize(dim); // need to call this when no layout manager is used.

    rhCellMouseAdapter = new RHCellMouseAdapter(this);

    // Adding the row header labels
    for (int ii = 0; ii < numRows; ii++) {
        addRow(ii, ii + 1, false);
    }

    JViewport viewPort = new JViewport();
    dim.height = rowHeight * numRows;
    viewPort.setViewSize(dim);
    viewPort.setView(rowHeaderPanel);
    scrollPane.setRowHeader(viewPort);

    // Experimental from the web, but I think it does the trick.
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (!ss.isEditing() && !e.isActionKey() && !e.isControlDown() && !e.isMetaDown() && !e.isAltDown()
                    && e.getKeyCode() != KeyEvent.VK_SHIFT && e.getKeyCode() != KeyEvent.VK_TAB
                    && e.getKeyCode() != KeyEvent.VK_ENTER) {
                log.error("Grabbed the event as input");

                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                if (rowIndexStart == -1 || colIndexStart == -1)
                    return;

                ss.editCellAt(rowIndexStart, colIndexStart);
                Component c = ss.getEditorComponent();
                if (c instanceof JTextComponent)
                    ((JTextComponent) c).setText("");
            }
        }
    });

    resizeAndRepaint();

    // Taken from a JavaWorld Example (But it works)
    KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false);

    Action ssAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SpreadSheet.this.actionPerformed(e);
        }
    };

    getInputMap().put(cut, "Cut");
    getActionMap().put("Cut", ssAction);

    getInputMap().put(copy, "Copy");
    getActionMap().put("Copy", ssAction);

    getInputMap().put(paste, "Paste");
    getActionMap().put("Paste", ssAction);

    ((JMenuItem) UIRegistry.get(UIRegistry.COPY)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.CUT)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.PASTE)).addActionListener(this);

    setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
}

From source file:org.paxml.selenium.rc.SeleniumHelper.java

static String[] getKeyCodes(char ch) {
    boolean shiftRequired = false;
    String key = String.valueOf(ch);
    String value = KEY_CODES_MAP.get(key);

    if (value != null) {
        shiftRequired = true;//from   w w w  .  ja v a  2  s.co  m
        key = value;
    } else if (Character.isUpperCase(key.charAt(0))) {
        shiftRequired = true;
    } else {
        key = key.toUpperCase();
    }

    KeyStroke ks = KeyStroke.getKeyStroke("pressed " + key.toUpperCase());
    int keyCode = 0;
    if (ks != null && ks.getKeyCode() != 0) {
        keyCode = ks.getKeyCode();
    } else {
        keyCode = CHAR_TO_KEY_CODE_MAP.get(key);
    }

    return shiftRequired ? new String[] { String.valueOf(KeyEvent.VK_SHIFT), String.valueOf(keyCode) }
            : new String[] { String.valueOf(keyCode) };
}

From source file:edu.ku.brc.af.ui.db.TextFieldWithQuery.java

/**
 * Processes the KeyEvent./*from w  w w  . j a  v  a 2s  .  com*/
 * @param ev event
 */
protected void cbxKeyReleased(KeyEvent ev) {
    if (isReadOnlyMode) {
        return;
    }
    if (ev.getKeyCode() == KeyEvent.VK_SHIFT || ev.getKeyCode() == KeyEvent.VK_LEFT
            || ev.getKeyCode() == KeyEvent.VK_RIGHT || ev.getKeyCode() == KeyEvent.VK_CONTROL
            || ev.getKeyCode() == KeyEvent.VK_META) {
        return;
    }

    currentText = textField.getText();
    if (uiFieldFormatter != null) {
        currentText = uiFieldFormatter.formatFromUI(currentText).toString();
    }
    if (currentText.length() == 0 || !hasNewText) {
        if (ev.getKeyCode() == KeyEvent.VK_TAB) {
            if (ev.isShiftDown()) {
                textField.transferFocusBackward();
            } else {
                textField.transferFocus();
            }
            return;
        }

        if (ev.getKeyCode() == JAutoCompComboBox.SEARCH_KEY || ev.getKeyCode() == KeyEvent.VK_DOWN) {
            showPopup(0); // add only
            return;
        }

        if (ev.getKeyCode() != KeyEvent.VK_ENTER) {
            // Add variable to track whether it once had a value and now it does not rods - 02/28/08

            idList.clear();
            list.clear();
            selectedId = null;

            // 02/09/08 - This should not be done here - rods
            // The reason is, that we may have added something only to remove
            // before leaving the control. So we should never send the notification
            // just because we delete the contents. (see wasCleared above)

            /*if (listSelectionListeners != null)
            {
            notifyListenersOfChange(TextFieldWithQuery.this);
            }*/
            //log.debug("setting hasNewText to true"); //$NON-NLS-1$
            hasNewText = true;
        }
    } else {
        hasNewText = true;
        //log.debug("setting hasNewText to true");
    }

    if (ev.getKeyCode() == JAutoCompComboBox.SEARCH_KEY || ev.getKeyCode() == KeyEvent.VK_TAB
            || ev.getKeyCode() == KeyEvent.VK_DOWN) {
        String origText = textField.getText();
        String text = origText;
        if (uiFieldFormatter != null && !uiFieldFormatter.isNumeric()) {
            text = uiFieldFormatter.formatFromUI(text).toString();
        }
        text = StringUtils.replace(text, "'", "\'");
        text = StringUtils.replace(text, "\"", "\\\"");

        // direction of focus change 1: forward 0: none -1: backwards
        int focusChange = (ev.isShiftDown() ? -1 : 1) * (ev.getKeyCode() == KeyEvent.VK_TAB ? 1 : 0);
        doQuery(text, origText, focusChange);
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPanel.java

/**
 * Shifts the text on the current line or the currently
 * selected text to the left one TAB./*  w ww. j  a v  a2  s.c  o m*/
 */
public void shiftTextLeft() {

    if (getSelectedText() == null) {

        int start = queryPane.getCurrentRowStart();
        int end = queryPane.getCurrentRowEnd();
        queryPane.shiftTextLeft(start, end);

    } else { // simulate a tab key for selected text

        try {

            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_SHIFT);
            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_SHIFT);

        } catch (AWTException e) {

            if (Log.isDebugEnabled()) {

                Log.error("Error simulating tab key events", e);
            }

        }

    }
}