This site requires JavaScript, please enable it in your browser!
Greenfoot back
darkmist255
darkmist255 wrote ...

2012/9/7

Is the tab key recognized by isKeyDown?

darkmist255 darkmist255

2012/9/7

#
Just wondering, the code Greenfoot.isKeyDown("tab") doesn't ever pick up, is it not recognized by Greenfoot? In the API it does list tab, so just wondering.
darkmist255 darkmist255

2012/9/8

#
Nevermind, managed to get it working. The working code is this:
1
2
3
4
5
6
7
8
9
10
11
12
JPanel panel = WorldHandler.getInstance().getWorldCanvas();
         
        panel.addKeyListener(new KeyListener() {
             
            public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_TAB) {/*action here*/};}
 
            public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_TAB) {/*action here*/};}
             
            public void keyTyped(KeyEvent e) {}
        });
        panel.setFocusTraversalKeysEnabled(false);
        panel.setFocusable(true);
davmac davmac

2012/9/8

#
That's messy - for one thing you're relying on undocumented internals (WorldHandler.getInstance()) and for another, you're breaking thread-safety (key presses will be handled on the Swing/AWT event thread instead of your scenario thread; there will be two threads accessing objects without any proper synchronization between them - the result may be occasional glitches, eg collision checking may break, or you may get exceptions in internal Greenfoot code). Trust me - you don't want to do that. I'll look into why tab doesn't work with Greenfoot.isKeyDown(...).
darkmist255 darkmist255

2012/9/8

#
Yeah I'm using it very skeptically at the moment, it doesn't have heavy use at the moment and I'm now keeping the keypress in a boolean (keyPressed sets it to true, then keyReleased sets it to false), this is helping to eliminate the synchronization problems (of which I experienced, which is why I am keeping its state stored). This code is mostly temporary as well, I know it's bad practice which is why I will replace it with something else once the opportunity comes, for now it's more of a "just in case". Also thanks for looking into it :D. Don't worry about me, I understand that there are many problems with this, I'd never rely on something "experimental" if you will.
You need to login to post a reply.