Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Keylistener not working. Need to loose focus on main window, and reapply it

800413Jun 30 2010 — edited Jul 2 2010
dear forum users.
Im having a bit of a problem with a keylistener.
To get it to work, i have to take focus away from the window (JFrame), and then back again..

My KeyListener:
public class KeyBinder implements KeyListener {
    private Map<Integer,CustomKeyEvent> keys = new HashMap<Integer,CustomKeyEvent>();
    

    public void keyReleased(KeyEvent e) {
        if (keys.containsKey(e.getKeyCode())) {
            keys.get(e.getKeyCode()).keyReleased(this);
        }
    }
    public void keyTyped(KeyEvent e) {
        if (keys.containsKey(e.getKeyCode())) {
            keys.get(e.getKeyCode()).keyTyped(this);
        }
    }
    public void keyPressed(KeyEvent e) {
        if (keys.containsKey(e.getKeyCode())) {
            keys.get(e.getKeyCode()).keyPressed(this);
        }
    }
I have also tried to just add a System.out.println in the beginning of keyPressed.. And no event is fired.

My JFrame:
    public JFrame_Main(String title, Dimension size) {
        super(title);
        setSize(size);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setFocusable(false);
    }
My Panel that should get focus:
public class JPanel_GameStarted_PlayingField extends JPanel implements TimerInterface {
    private Timer timer;
    public JPanel_GameStarted_PlayingField() {
        addKeyListener(Information.getKeyBinder());
        setVisible(false);
        setSize(Information.getMainFrame().getSize().width - 8, Information.getMainFrame().getSize().height - 50);
        setLocation(0,0);
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        addMouseListener(new CustomMouseListener(Information.getGameController().getSelf()));
        
        timer = new Timer();

        timer.scheduleAtFixedRate(new ExtendedTimerTask(this), 0, 20);
        setFocusable(true);
        setVisible(true);
        requestFocus();
    }
The strange thing is, the mouselistener works fine..
Anyone know what might be wrong?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 30 2010
Added on Jun 30 2010
2 comments
2,281 views