Returns whether a JComponent listens for a key code, i.e. - Java Swing

Java examples for Swing:JComponent

Description

Returns whether a JComponent listens for a key code, i.e.

Demo Code


//package com.java2s;

import javax.swing.*;

public class Main {
    /**//  w  w  w  .ja v a  2  s.  com
     * Returns whether a component listens for a key code, i.e. it has an 
     * action associated with the key code.
     * @param component The component to examine.
     * @param keyCode The key code to test.
     * @return True if the component listens for the key code, false otherwise.
     */
    static public boolean componentListensForKey(JComponent component,
            int keyCode) {
        KeyStroke[] keyStrokes = component.getInputMap().allKeys();
        if (keyStrokes == null)
            return false;
        for (int i = keyStrokes.length - 1; i >= 0; i--) {
            if (keyCode == keyStrokes[i].getKeyCode()) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials