Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid that pressing the ALT key takes away the focus from my GUI

Tags:

java

swing

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);
}
}
like image 863
räph Avatar asked May 15 '09 13:05

räph


1 Answers

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!!

like image 73
räph Avatar answered Nov 10 '22 17:11

räph