Adds a listener to a dialog, which will fire when a key is pressed. - Java Swing

Java examples for Swing:JDialog

Description

Adds a listener to a dialog, which will fire when a key is pressed.

Demo Code


//package com.java2s;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.KeyStroke;

public class Main {
    /**//w  w  w . ja va  2s  .c o m
     * Adds a listener to a dialog, which will fire when a key is pressed.
     * @param dialog the dialog
     * @param key the key (see constants in {@link KeyEvent})
     * @param listener the listener
     */
    public static void onKeyPress(JDialog dialog, int key,
            ActionListener listener) {
        dialog.getRootPane().registerKeyboardAction(listener,
                KeyStroke.getKeyStroke(key, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    /**
     * Adds all the listeners of a button to a dialog, which will fire when a
     * key is pressed.
     * @param dialog the dialog
     * @param key the key (see constants in {@link KeyEvent})
     * @param button the button
     */
    public static void onKeyPress(JDialog dialog, int key,
            final AbstractButton button) {
        dialog.getRootPane().registerKeyboardAction(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (ActionListener listener : button
                                .getActionListeners()) {
                            listener.actionPerformed(e);
                        }
                    }
                }, KeyStroke.getKeyStroke(key, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);
    }
}

Related Tutorials