Current Position:Home > Focus problem using key event

Focus problem using key event

Update:11-30Source: network consolidation
Advertisement
Hi!
There is an application I've created uses key event that needs your help.
As you know, that setting 'Mnemonic' to a JButton object makes the button accessible by a key mentioned in the parameter as the following ->
               OkButton.setMnemonic(KeyEvent.VK_O);Now, pressing 'Alt' and 'O' keys together will do the same action as the 'OKButton' does.
But as of me, I think pressing two keys together is not a complete handy job.
So, is there any code that will do the same, by pressing only the 'O' key ?
Ok! I know that there is something to be taken care of; that is, if I want the button to react by pressing only the 'O' key the button must be in focus [value returned by the method [code]isFocusable() for the button must return true.]
Then how the 'Mnemonic' works ?!! When 'Mnemonic' do something, button does not have any focus.
Only, I press the Alt+O and the work done successfully! No need to take care wherever the focus is. So, is there any way to do alike, where I don't have to manage the focus subsystem?? I would only press the 'O' key and the task will be done.
Please send a sample code. Thanks!

The Best Answer

Advertisement
I suggest you look into Key Bindings:
"How to Use Key Bindings"
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
Here is a short demo program that uses Key Bindings to do what you describe:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class PressOTest extends JFrame {
    public PressOTest() {
        super("Press O or C");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // Action that will be associated with the OK button and with
        // the 'O' key event
        Action okAction = new AbstractAction("Ok") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(PressOTest.this, "Ok!");
        // Action that will be associated with the Cancel button and with
        // the 'C' key event
        Action cancelAction = new AbstractAction("Cancel") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(PressOTest.this, "Cancel!");
        // Register Key Bindings for the 'O' and 'C' keys:
        InputMap im = getRootPane().getInputMap(
                JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap am = getRootPane().getActionMap();
        im.put(KeyStroke.getKeyStroke( KeyEvent.VK_O, 0 ), "ok");
        am.put( "ok", okAction );
        im.put(KeyStroke.getKeyStroke( KeyEvent.VK_C, 0 ), "cancel");
        am.put( "cancel", cancelAction );
        // Create and add OK & Cancel buttons:
        JButton okButton = new JButton(okAction);
        JButton cancelButton = new JButton(cancelAction);
        Box box = Box.createHorizontalBox();
        box.add( Box.createHorizontalGlue() );
        box.add( okButton );
        box.add( Box.createHorizontalStrut(10) );
        box.add( cancelButton );
        box.add( Box.createHorizontalGlue() );
        getContentPane().add( box );
        setSize(300, 300);
        setLocationRelativeTo(null);
    public static void main(String[] args) {
        new PressOTest().setVisible(true);
}
  • Focus problem using key event Update:11-30

    Hi! There is an application I've created uses key event that needs your help. As you know, that setting 'Mnemonic' to a JButton object makes the button accessible by a key mentioned in the parameter as the following ->                OkButton.setMnem

  • Help with understanding key event propagation Update:11-30

    Hello, I am hoping someone can help me understand a few things which are not clear to me with respect to handling of key events by Swing components. My understanding is summarized as: (1) Components have 3 input maps which map keys to actions one for

  • Getting Key Events during animation loop Update:11-30

    I'm having a problem recieving Key events during my animation loop. Here is my example program import java.awt.*; import java.awt.image.BufferStrategy; import javax.swing.JPanel; import javax.swing.ImageIcon; import javax.swing.JFrame; import java.ut

  • Safely switching focus during backspace key down event? Update:11-30

    I have a simple form that I'm building. It has a variable length list of entries, and I'm using a TextInput for each entry. Because the list is variable in length, I'm allowing the user to delete elements from the list. One of the ways they can do th

  • KeyListener Problems with Directional Key events Update:11-30

    Here's the problem: If I press and hold the up and right directional keys (non-numpad) and then press the left directional key, it doesn't recognize that I pressed left (i.e. "LeftKeyPressed" is not printed). What's up? Is there something I don'

  • Key event without focus Update:11-30

    Hi, Could you tell me how to get F1 key event which is nothing to do with any control's focuses? For example, suppose there's a button saying "F1 exit", and the focus is on some other button. In such case, if user pushes F1, program should exits

  • Calling1.4.1 signed applet from Javascript causes keyboard/focus problems Update:10-11

    Pretty sure there's a JRE bug here, but I'm posting to forums before I open one in case I'm missing something obvious :-) This issue may be specific to IE, I haven't tested elsewhere yet. Our web application is centered around a signed applet that is

  • JPanel can't receive key events Update:11-30

    I have a single JPanel added to the content pane of a JFrame. I want to itercept key events by adding a KeyListener to the JPanel. If I do it, I don't receive key events. To solve the problem I identified two ways: - add the KeyListener to the JFrame

  • Focus manager - transfer focus problem Update:11-30

    Hi, Have three main components in my application that handles the tab and shift tab orders through a focus manager The problem arises when I open a dialog window and have a bunch of TextFields and the focus manager is looking at my tabs. My Dialog co

  • Something is eating my key events! Update:11-30

    Okay, so I am trying to add some key events to a game. I have added this listener to a class I called Background:           this.addKeyListener(new java.awt.event.KeyAdapter() {                public void keyPressed(java.awt.event.KeyEvent e) {