tags:

views:

550

answers:

2

I'm developing a java app with swing in Windows.

The problem is: after pressing (and releasing) the ALT key, the next key press has no effect (there won't be a keyPressed event fired). Only the releasing the next key will be recognized. Pressing and releasing CTRL or SHIFT after ALT has no effect at all. The you first have to press another key or click into the component to receive key events from CTRL or SHIFT again.

Probably Windows takes the focus away from my GUI component to the title/menu of the frame. I need ALT+MouseWheel to move a graphic in my app, if I afterwards wants to zoom the graphic with CTRL+MouseWheel this won't be working. So howe to stop ALT from taking away the focus (but still be able to access a menuItem with e.g. ALT+F)?

I already tried Component.requestFocus() - but actually my component doesn't lose the focus really.

A simple example which shows the behaviour:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

class MyKeyListener implements KeyListener {
public void keyTyped(KeyEvent arg0) {}

public void keyPressed(KeyEvent arg0) {
 System.out.println("Key perssed: " + arg0.getKeyCode());
} 
public void keyReleased(KeyEvent arg0) {
 System.out.println("Key released: " + arg0.getKeyCode());
}
}

public class KeyListenerDemo {

public static void main(String[] a) {
    JFrame frame = new JFrame("Keytest");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setFocusTraversalKeysEnabled(true);
    JTextField textField = new JTextField();
    textField.addKeyListener(new MyKeyListener());
    frame.add(textField);
    frame.setSize(300, 200);
    frame.setVisible(true);
}
}
A: 

I don't think it is possible, at least not in swing. Every single swing application that I ever used had the same problem. It is one of the main reasons I gave up using Netbeans IDE, although the IDE is generaly very nice. SWT applications don't have that problem.

Dev er dev
I was already afraid to get that answer ;( but isn't there some workaround to gain the key-focus again?
räph
Not that I know of.
Dev er dev
A: 

In my case the following worked: KeyEvent.consume()

Consumes this event so that it will not be processed in the default manner by the source which originated it.

This stops Windows from stealing my focus, but I'm still able to access my menuitems with the keyboard mnemonics with ALT.

Thanks to Scott W for his comment!!

räph