Java Code Examples for java.awt.event.KeyListener

The following examples show how to use java.awt.event.KeyListener. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: KodeBeagle   Source File: ProjectTree.java    License: Apache License 2.0 6 votes vote down vote up
public final KeyListener getKeyListener() {
    return new KeyAdapter() {
        @Override
        public void keyTyped(final KeyEvent keyEvent) {
            super.keyTyped(keyEvent);
            if (keyEvent.getKeyChar() == KeyEvent.VK_ENTER) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
                        windowObjects.getjTree().getLastSelectedPathComponent();
                if (selectedNode.isLeaf()) {
                    final CodeInfo codeInfo = (CodeInfo) selectedNode.getUserObject();
                    try {
                        showEditor(codeInfo);
                    } catch (Exception e) {
                        KBNotification.getInstance().error(e);
                        e.printStackTrace();
                    }
                }
            }
        }
    };
}
 
Example 2
private boolean processComponentKeyListeners(KeyEvent keyEvent) {

		Component focusOwner = focusProvider.getFocusOwner();
		if (focusOwner == null) {
			return false;
		}

		KeyListener[] keyListeners = focusOwner.getKeyListeners();
		for (KeyListener listener : keyListeners) {
			int id = keyEvent.getID();
			switch (id) {
				case KeyEvent.KEY_TYPED:
					listener.keyTyped(keyEvent);
					break;
				case KeyEvent.KEY_PRESSED:
					listener.keyPressed(keyEvent);
					break;
				case KeyEvent.KEY_RELEASED:
					listener.keyReleased(keyEvent);
					break;
			}
		}

		return keyEvent.isConsumed();
	}
 
Example 3
Source Project: ghidra   Source File: SymbolTablePluginTest.java    License: Apache License 2.0 6 votes vote down vote up
private void triggerAutoLookup(String text) throws Exception {

		KeyListener listener = (KeyListener) getInstanceField("autoLookupListener", symbolTable);

		BiConsumer<Component, KeyEvent> consumer = (c, e) -> {
			if (e.getID() != KeyEvent.KEY_PRESSED) {
				return;
			}
			runSwing(() -> listener.keyPressed(e));
		};

		// use the version of triggerText that allows us to consume the event directly, bypassing
		// the focus system
		triggerText(symbolTable, text, consumer);
		waitForNotBusy(symbolTable);
	}
 
Example 4
Source Project: freecol   Source File: Canvas.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes components that is only used when in game.
 */
public void removeInGameComponents() {
    // remove listeners, they will be added when launching the new game...
    KeyListener[] keyListeners = getKeyListeners();
    for (KeyListener keyListener : keyListeners) {
        removeKeyListener(keyListener);
    }

    MouseListener[] mouseListeners = getMouseListeners();
    for (MouseListener mouseListener : mouseListeners) {
        removeMouseListener(mouseListener);
    }

    MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners();
    for (MouseMotionListener mouseMotionListener : mouseMotionListeners) {
        removeMouseMotionListener(mouseMotionListener);
    }

    for (Component c : getComponents()) {
        removeFromCanvas(c);
    }
}
 
Example 5
Source Project: Pixelitor   Source File: DialogFooter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void addFocusArrowListener(JComponent jc) {
    /* Check to see if someone already added this kind of listener:
     */
    KeyListener[] listeners = jc.getKeyListeners();
    for (KeyListener listener : listeners) {
        if (listener instanceof FocusArrowListener) {
            return;
        }
    }
    //Add our own:
    jc.addKeyListener(new FocusArrowListener());
}
 
Example 6
Source Project: pumpernickel   Source File: DialogFooter.java    License: MIT License 5 votes vote down vote up
private static void addFocusArrowListener(JComponent jc) {
	/**
	 * Check to see if someone already added this kind of listener:
	 */
	KeyListener[] listeners = jc.getKeyListeners();
	for (int a = 0; a < listeners.length; a++) {
		if (listeners[a] instanceof FocusArrowListener)
			return;
	}
	// Add our own:
	jc.addKeyListener(new FocusArrowListener());
}
 
Example 7
Source Project: TrakEM2   Source File: DNDTree.java    License: GNU General Public License v3.0 5 votes vote down vote up
public DNDTree(final Project project, final DefaultMutableTreeNode root, final Color background) {
	this.project = project;
	this.background = background;
	setAutoscrolls(true);
	setModel(new DefaultTreeModel(root));
	setRootVisible(true); 
	setShowsRootHandles(false);//to show the root icon
	getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); //set single selection for the Tree
	setEditable(true);
	//DNDTree.expandAllNodes(this, root);
	// so weird this instance below does not need to be kept anywhere: where is Java storing it?
	dtth = new DefaultTreeTransferHandler(project, this, DnDConstants.ACTION_COPY_OR_MOVE);
	//
	this.setScrollsOnExpand(true);
	KeyListener[] kls = getKeyListeners();
	if (null != kls) for (KeyListener kl : kls) { Utils.log2("removing kl: " + kl); removeKeyListener(kl); }
	//resetKeyboardActions(); // removing the KeyListeners is not enough!
	//setActionMap(new ActionMap()); // an empty one -- none of these two lines has any effect towards stopping the key events.
	this.addKeyListener(this);

	if (null != background) {
		final DefaultTreeCellRenderer renderer = createNodeRenderer();
		renderer.setBackground(background);
		renderer.setBackgroundNonSelectionColor(background);
		// I hate swing, I really do. And java has no closures, no macros, and reflection is nearly as verbose as the code below!
		SwingUtilities.invokeLater(new Runnable() { public void run() {
			DNDTree.this.setCellRenderer(renderer);
		}});
		SwingUtilities.invokeLater(new Runnable() { public void run() {
			DNDTree.this.setBackground(background);
		}});
	}
}
 
Example 8
Source Project: trygve   Source File: MessageConsole.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void reinitialize() {
	// Here we set in_ to the MessageConsole's textComponent,
	// for fetching from elsewhere. I wonder if it should be
	// instead set to the error panel? That's passed in the
	// above constructor. But that ends up here, bound anyhow
	// to the error panel.
	
	if (null != in_) {
		textComponent.removeKeyListener(in_);
		try {
			in_.close();
		} catch (IOException ioex) {
			// who cares?
		}
		in_ =  null;
	}

	in_ = new InputStreamClass.DocInputStream(textComponent, this);
	
	// We want input to come here. See also setFocusable.
	// This ends binding to the errorPanel:
	//
	//	... errorPanel = new javax.swing.JTextPane();
	
       textComponent.setFocusable(true);
       
       // Make sure there are no other listeners
       final EventListener[] els = textComponent.getListeners(EventListener.class);
       for (final EventListener listener : els) {
       	if (listener instanceof KeyListener) {
       		textComponent.removeKeyListener((KeyListener)listener);
       	}
       }
       
       textComponent.addKeyListener(in_);
}
 
Example 9
/**
 * Maps {@code Component.removeKeyListener(KeyListener)} through queue
 */
public void removeKeyListener(final KeyListener keyListener) {
    runMapping(new MapVoidAction("removeKeyListener") {
        @Override
        public void map() {
            getSource().removeKeyListener(keyListener);
        }
    });
}
 
Example 10
Source Project: NBANDROID-V2   Source File: KeyEditor.java    License: Apache License 2.0 5 votes vote down vote up
public KeyEditor(KeyListener listener) {
    initComponents();
    passwd1.setText("");
    passwd2.setText("");
    passwd1.addKeyListener(listener);
    passwd2.addKeyListener(listener);
    alias.addKeyListener(listener);
    firstAndLastName.addKeyListener(listener);
    organizationUnit.addKeyListener(listener);
    organization.addKeyListener(listener);
    city.addKeyListener(listener);
    stateOrProvince.addKeyListener(listener);
    countryCode.addKeyListener(listener);
}
 
Example 11
/**
 * Invoked when a key has been typed. See the class description for {@link java.awt.event.KeyEvent} for a definition
 * of a key typed event.
 */
public void keyTyped( final KeyEvent e ) {
  final KeyListener[] keyListeners = listenerList.getListeners( KeyListener.class );
  for ( int i = 0; i < keyListeners.length; i++ ) {
    final KeyListener keyListener = keyListeners[ i ];
    keyListener.keyTyped( e );
  }
}
 
Example 12
Source Project: jexer   Source File: SwingComponent.java    License: MIT License 5 votes vote down vote up
/**
 * Adds the specified key listener to receive key events from this
 * component. If l is null, no exception is thrown and no action is
 * performed.
 *
 * @param l the key listener.
 */
public void addKeyListener(KeyListener l) {
    if (frame != null) {
        frame.addKeyListener(l);
    } else {
        component.addKeyListener(l);
    }
}
 
Example 13
Source Project: SNT   Source File: SimpleNeuriteTracer.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method will remove the existing keylisteners from the component 'c',
 * tells 'firstKeyListener' to call those key listeners if it has not dealt
 * with the key, and then sets 'firstKeyListener' as the key listener for
 * 'c'
 */
public static void setAsFirstKeyListener(final Component c, final QueueJumpingKeyListener firstKeyListener) {
	final KeyListener[] oldKeyListeners = c.getKeyListeners();
	for (final KeyListener kl : oldKeyListeners) {
		c.removeKeyListener(kl);
	}
	firstKeyListener.addOtherKeyListeners(oldKeyListeners);
	c.addKeyListener(firstKeyListener);
}
 
Example 14
Source Project: amidst   Source File: ProfileSelectPanel.java    License: GNU General Public License v3.0 5 votes vote down vote up
@CalledOnlyBy(AmidstThread.EDT)
public KeyListener createKeyListener() {
	return new KeyAdapter() {
		@CalledOnlyBy(AmidstThread.EDT)
		@Override
		public void keyPressed(KeyEvent e) {
			if (!isLoading()) {
				doKeyPressed(e.getKeyCode());
			}
		}
	};
}
 
Example 15
Source Project: SNT   Source File: QueueJumpingKeyListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void keyReleased(final KeyEvent e) {
	for (final KeyListener kl : listeners) {
		if (e.isConsumed())
			break;
		kl.keyReleased(e);
	}
}
 
Example 16
Source Project: 07kit   Source File: KeyboardExtension.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Invoked when a key has been pressed.
 * See the class description for {@link KeyEvent} for a definition of
 * a key pressed event.
 */
public void keyPressed(KeyEvent e) {
    for (KeyListener child : children) {
        child.keyPressed(e);
        if (e.isConsumed()) {
            return;
        }
    }

    if (acceptingEvents) {
        _keyPressed(e);
    }
}
 
Example 17
Source Project: 07kit   Source File: KeyboardExtension.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Invoked when a key has been typed.
 * See the class description for {@link KeyEvent} for a definition of
 * a key typed event.
 */
public void keyTyped(KeyEvent e) {
    for (KeyListener child : children) {
        child.keyTyped(e);
        if (e.isConsumed()) {
            return;
        }
    }

    if (acceptingEvents) {
        _keyTyped(e);
    }
}
 
Example 18
Source Project: Lunar   Source File: Game.java    License: MIT License 5 votes vote down vote up
/**
 * Clear all key listeners. NOTE: this method will also remove the default listener.
 */
public void clearKeyListeners() {
    KeyListener[] listeners = frame.getKeyListeners();
    for (KeyListener listener : listeners) {
        removeKeyListener(listener);
    }
}
 
Example 19
Source Project: netbeans   Source File: ListView.java    License: Apache License 2.0 5 votes vote down vote up
private void setupSearch() {
    // Remove the default key listeners
    KeyListener[] keyListeners = getListeners(KeyListener.class);

    for (int i = 0; i < keyListeners.length; i++) {
        removeKeyListener(keyListeners[i]);
    }

    // Add new key listeners
    addKeyListener(
        new KeyAdapter() {
        @Override
            public void keyPressed(KeyEvent e) {
                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)) {
                    searchTextField.setText(String.valueOf(c));
                    displaySearchField();
                }
            }
        }
    );

    // Create a the "multi-event" listener for the text field. Instead of
    // adding separate instances of each needed listener, we're using a
    // class which implements them all. This approach is used in order
    // to avoid the creation of 4 instances which takes some time
    SearchFieldListener searchFieldListener = new SearchFieldListener();
    searchTextField.addKeyListener(searchFieldListener);
    searchTextField.addFocusListener(searchFieldListener);
    searchTextField.getDocument().addDocumentListener(searchFieldListener);
}
 
Example 20
/**
 * Maps {@code Component.addKeyListener(KeyListener)} through queue
 */
public void addKeyListener(final KeyListener keyListener) {
    runMapping(new MapVoidAction("addKeyListener") {
        @Override
        public void map() {
            getSource().addKeyListener(keyListener);
        }
    });
}
 
Example 21
Source Project: netbeans   Source File: ColumnModels.java    License: 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 22
Source Project: gcs   Source File: NumberFilter.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new numeric key entry filter.
 *
 * @param field        The {@link JTextField} to filter.
 * @param allowDecimal Pass in {@code true} to allow floating point.
 * @param allowSign    Pass in {@code true} to allow sign characters.
 * @param allowGroup   Pass in {@code true} to allow group characters.
 * @param maxDigits    The maximum number of digits (not necessarily characters) the field can
 *                     have.
 */
public NumberFilter(JTextField field, boolean allowDecimal, boolean allowSign, boolean allowGroup, int maxDigits) {
    mField = field;
    mAllowDecimal = allowDecimal;
    mAllowSign = allowSign;
    mAllowGroup = allowGroup;
    mMaxDigits = maxDigits;
    for (KeyListener listener : mField.getKeyListeners()) {
        if (listener instanceof NumberFilter) {
            mField.removeKeyListener(listener);
        }
    }
    mField.addKeyListener(this);
}
 
Example 23
private KeyListener customKeyListener() {
    final KeyAdapter adapter = new KeyAdapter() {

        @Override
        public void keyTyped(KeyEvent e) {

            String modifiedQuery = "(?i)" + searchField.getText();
            tableRowShorter.setRowFilter(RowFilter.regexFilter(modifiedQuery));

            super.keyTyped(e);
        }

    };
    return adapter;
}
 
Example 24
Source Project: 07kit   Source File: KeyboardExtension.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Invoked when a key has been released.
 * See the class description for {@link KeyEvent} for a definition of
 * a key released event.
 */
public void keyReleased(KeyEvent e) {
    for (KeyListener child : children) {
        child.keyReleased(e);
        if (e.isConsumed()) {
            return;
        }
    }

    if (acceptingEvents) {
        _keyReleased(e);
    }
}
 
Example 25
private KeyListener getKeyListener() {
	KeyAdapter listener = new KeyAdapter() {
		@Override
		public void keyTyped(KeyEvent e) {
			char c = e.getKeyChar();
			if(Character.isLetter(c) && !e.isAltDown()) {
				e.consume();
			}
		}
	};
	return listener;
}
 
Example 26
public static JTextField createTextField(String text, KeyListener listener, boolean numbers)
{
    JTextField field = new JTextField(text);
    field.setMinimumSize(textPrefSize);
    if(text.length() == 0)
        field.setPreferredSize(textPrefSize);
    if(listener != null)
        field.addKeyListener(listener);
    if(numbers)
        field.setDocument(new NumberDocument());
    return field;
}
 
Example 27
Source Project: consulo   Source File: ListDelegationUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static ActionCallback installKeyboardDelegation(final JComponent focusedComponent, final JList delegateTo) {
  final KeyListener keyListener = new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
      final int code = e.getKeyCode();
      final int modifiers = e.getModifiers();
      switch (code) {
        case KeyEvent.VK_UP:
          ScrollingUtil.moveUp(delegateTo, modifiers);
          break;
        case KeyEvent.VK_DOWN:
          ScrollingUtil.moveDown(delegateTo, modifiers);
          break;
        case KeyEvent.VK_HOME:
          ScrollingUtil.moveHome(delegateTo);
          break;
        case KeyEvent.VK_END:
          ScrollingUtil.moveEnd(delegateTo);
          break;
        case KeyEvent.VK_PAGE_UP:
          ScrollingUtil.movePageUp(delegateTo);
          break;
        case KeyEvent.VK_PAGE_DOWN:
          ScrollingUtil.movePageDown(delegateTo);
          break;
      }
    }
  };

  focusedComponent.addKeyListener(keyListener);

  final ActionCallback callback = new ActionCallback();
  callback.doWhenProcessed(() -> focusedComponent.removeKeyListener(keyListener));
  return callback;
}
 
Example 28
Source Project: dragonwell8_jdk   Source File: Test4498236.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void removeKeyListener(KeyListener listener) {
    remove(listener);
}
 
Example 29
Source Project: dragonwell8_jdk   Source File: Test4498236.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void add(KeyListener listener) {
}
 
Example 30
Source Project: dragonwell8_jdk   Source File: Test4498236.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void remove(KeyListener listener) {
}