Java examples for Swing:Key Event
add Key Listener To All Component
//package com.java2s; import java.awt.Component; import java.awt.Container; import java.awt.event.KeyListener; import javax.swing.AbstractButton; import javax.swing.JComponent; public class Main { public static void addKeyListenerToAll(Component parent, KeyListener listener) { if (parent instanceof AbstractButton) { AbstractButton a = (AbstractButton) parent; // Check If The Listener is Already There (Avoid Double Reactions) boolean is = false; KeyListener[] kl = a.getKeyListeners(); for (KeyListener k : kl) { if (k.equals(listener)) { is = true;/*from w ww . j a va 2 s.c o m*/ break; } } if (!is) a.addKeyListener(listener); } else if (parent instanceof JComponent) { JComponent a = (JComponent) parent; // Check If The Listener is Already There (Avoid Double Reactions) boolean is = false; KeyListener[] kl = a.getKeyListeners(); for (KeyListener k : kl) { if (k.equals(listener)) { is = true; break; } } if (!is) a.addKeyListener(listener); } if (parent instanceof Container) { Component[] comps = ((Container) parent).getComponents(); for (Component c : comps) { addKeyListenerToAll(c, listener); } } } }