Getting Key Events during animation loop

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.util.ArrayList;
import java.awt.event.*;
import java.util.Iterator;
import GAME.graphics.Animation;
import GAME.sprites.MainPlayer;
import GAME.util.MapData;
import GAME.input.*;
public class ImageTest extends JFrame {
    private static final long DEMO_TIME = 20000;
    private Animation      anim;
    private MainPlayer     mPlayer;
    private MapData               mapData;
    private InputManager      inputManager;
    private GameAction moveLeft;
    private GameAction moveRight;
    private GameAction exit;
    public ImageTest()
     requestFocus();
     initInput();
     setSize(1024, 768);
     setUndecorated(true);
     setIgnoreRepaint(true);
     setResizable(false);
     loadImages();
     anim = new Animation();
        mPlayer = new MainPlayer(anim);
        setVisible(true);
        createBufferStrategy(2);
        animationLoop();
     // load the player images
     private void loadImages()
          // code that loads images...
     // Initialize input controls
     private void initInput() {
        moveLeft = new GameAction("moveLeft");
        moveRight = new GameAction("moveRight");
        exit = new GameAction("exit",
            GameAction.DETECT_INITAL_PRESS_ONLY);
        inputManager = new InputManager(this);
        inputManager.setCursor(InputManager.INVISIBLE_CURSOR);
        inputManager.mapToKey(moveLeft, KeyEvent.VK_LEFT);
        inputManager.mapToKey(moveRight, KeyEvent.VK_RIGHT);
        inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
    // Check player input
    private void checkInput(long elapsedTime) {
        if (exit.isPressed()) {
            System.exit(0);
        if (mPlayer.isAlive()) {
            float velocityX = 0;
            if (moveLeft.isPressed()) {
                velocityX-=mPlayer.getMaxSpeed();
            if (moveRight.isPressed()) {
                velocityX+=mPlayer.getMaxSpeed();
            mPlayer.setVelocityX(velocityX);
    // main animation loop
    public void animationLoop() {
        long startTime = System.currentTimeMillis();
        long currTime = startTime;
        while (currTime - startTime < DEMO_TIME) {
            long elapsedTime =
                System.currentTimeMillis() - currTime;
            currTime += elapsedTime;
            checkInput(elapsedTime);
            mPlayer.update(elapsedTime);
            // draw and update screen
            BufferStrategy strategy = this.getBufferStrategy();
            Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
            if (!(bgImage == null))
                 draw(g);
                 g.dispose();
                 if (!strategy.contentsLost()) {
                     strategy.show();
            // take a nap
            try {
                Thread.sleep(20);
            catch (InterruptedException ex) { }
    public void draw(Graphics g) {
        // draw background
        if (bgImage != null)
                     // draw image
             g.drawImage(mPlayer.getImage(), (int)mPlayer.getX(), (int)mPlayer.getY(), null);
}My InputManager implements KeyListener. When running print statements on my Key events, they are not being called until after the animation demo is done running. Can someone help me with getting the Key events to update during the animation loop? Thank you!

I've used the post from Abuse on the following thread with success. Maybe it will clue you in to what you might be doing wrong:
http://forum.java.sun.com/thread.jsp?forum=406&thread=498527

Similar Messages

  • Getting key events without a jcomponent...

    Is it possible to get key events without adding a keylistener to a jpanel? I want a class of mine to manage input of it's own, but it has no reference to a jpanel. They don't necessarily have to be KeyEvents, but just some way to detect if a key has been pressed (like the arrow keys). How can I do this? Thanks.

    Lots of components can listen for key events.
    What does your class subclass?It doesn't subclass anything. I am creating a custom menu system for my game using images I have made for the tileset. I would like it to handle some keyboard events of its own. (Like if the down arrow is pressed, it will move the focus down to the next component on its own). Right now I am currently passing the key events from my fullscreen jpanel to the menu class and it is handling them that way. Thanks.

  • How to distinguish is cell get key event or mouse event in table?

    Hi!
    I have a JTable.
    1.Select cell and double click. As result caret is show
    2.Select cell and start type. As result caret is show
    How distinguish is caret is show, because cell get mouse event or key event?
    Thank you.

    Hm ...
    the problem with the key events is, that they are partically taking place in an editor component - but the double click of the mouse clicked on a cell, which is not currently edited, can be get by a MouseListener added to the JTable.
    My idea to that is as follows - hold the double_clicked state in a boolean variable hold by your JTable subclass - it is set by a MouseListener added to the JTable - and reset by the overwritten prepareEditor(...) method. This method should do the following:
    // say, double_clicked is a boolean field in your JTable subclass
    public Component prepareEditor(TableCellEditor editor,int row,int column) {
    Component c = super.prepareEditor(editor,row,column);
    if ((!double_clicked)&&(c instanceof JTextField)) { ((JTextField) c).setText(""); }
    double_clicked = false;
    return c;
    }now you have only to implement an add a MouseListener to your JTable subclass which detects this double click and sets the double_clicked field accordingly.
    This is an idea on the fly - hope it is helpful for you.
    greetings Marsian

  • Not getting key events.

    Okay have a really odd issue. I have a frame that contains a custom panel that contains a custom canvas. I it setting the focus to the canvas when it opens but I don't seem to be getting key strokes!
    When you change the focus from the frame to another window and click back again you do get the keystrokes but the request focus call seems to only sort of work!
    Any suggestions?

    lwatcdr wrote:
    Already did that and not joy.
    The odd thing is that it used to work and I can not figure out for the life of me why it stopped!
    I have started to move the application over to Swing so some of the dialogs are now Swing with the main window still in AWT. I am working on porting that part to Swing but it is a big dynamic custom document so it is taking a while.Let's just quit with the guessing then, post your code.

  • Do not get key events when HContainer object is added to HScene

    Experts,
    Please help, I am missing something simple.
    I am creating an container (mCurrentContainer) with some buttons in them as follows,
              mRecListButton = new HTextButton("List", curX, curY);
              add(mRecListButton);
              // Setup a recording
              curY += V3Button.mHeight + gap;
              mRecButton = new HTextButton("Record", curX , curY);
              add(mRecButton);
              // Shows the list of scheduled recordings
              curY += V3Button.mHeight + gap;
              mScheduleRecButton = new HTextButton("Schedule", curX , curY);
              add(mScheduleRecButton);
              // Shows the list of Series Recordings
              curY += V3Button.mHeight + gap;
              mSeriesRecButton = new HTextButton("Series", curX, curY);
              add(mSeriesRecButton);
              mCurrentSelectedButton = LISTVALUE;
              mRecListButton.setFocus();
    Then I am creating a scene,
              HSceneFactory factory = HSceneFactory.getInstance();
              HSceneTemplate sceneTemplate = new HSceneTemplate();
              sceneTemplate.setPreference(HSceneTemplate.
                             SCENE_PIXEL_DIMENSION,
                             new Dimension(640, 400),
                             HSceneTemplate.REQUIRED);
              sceneTemplate.setPreference(HSceneTemplate.
                             SCENE_SCREEN_LOCATION,
                             new HScreenPoint((float)0,(float)0),
                             HSceneTemplate.REQUIRED);
              mScene = factory.getBestScene(sceneTemplate);
              mScene.requestFocus();
              mScene.addFocusListener(this);
    Then, I add the above container to the mscene as follows,
    mCurrentContainer = myContainer;
    mScene.add(mCurrentContainer); // Keys Presses do not work if left uncommented
    mScene.setVisible(true);
    mScene.requestFocus();
    mScene.addKeyListener( mCurrentContainer);
    mCurrentContainer.setVisible(true);
    mCurrentContainer.requestFocus();
    I see the buttons correctly and the "List" button is highlighted correctly. However, I do not get any key presses.
    Now, if I comment out "mScene.add()" as follows,
    mCurrentContainer = myContainer;
    // mScene.add(mCurrentContainer); // Now the key presses works correctly.
    mScene.setVisible(true);
    mScene.requestFocus();
    mScene.addKeyListener( mCurrentContainer);
    mCurrentContainer.setVisible(true);
    mCurrentContainer.requestFocus();
    The key presses works correctly. However, the buttons are not displayed now.
    What am I missing?
    Thanks!

    I have not tried the above suggestions but the problem is solved. The issue was - I had the requirement of creating a a default child record when the parent record is created. I was creating the child record using insert statement in Prepared Statement in the doDML of parent EOImpl. So it is not creating a row in the EO and when I add the second record through the application and save, the getRowCount returns 1 which is new record that created through application. Sorry for not providing this info earlier and Thank You all.
    Regards, Pradeep

  • Multiple key events during high workload

    Hi,
    When my machine is busy it happens that letters get repeated, something like `baaad' with the input of `bad'. Is this a known problem? Is it hardware related? Is it OS related? Is it fixed in Leopard?
    I worked on Linux before and I never had such problems with Linux.
    By the way, when my MacBook Pro ejects the disc the rest of the machine does not respond to anything ...
    Best wishes
    Stefan

    You can adjust the key rate via System Preferences>Keyboard & Mouse>Keyboard.

  • How to catch key events

    Hello!
    I have a component which extends JPanel. Now I dynamically add a JTextField as a child to this component. The problem is: when the textfield has focus, how can I get key events in my panel before the textfield gets them (and maybe intercept them so that the textfield doesn't get them at all)?
    Background: the component is a self written table and the textfield is an editor. Now I have to make sure that when I am editing and press e.g. "cursor up", that not the textfield will get this key event but the table (which should traverse the current cell then ...)
    The problem is: I cannot change the textfield (extend it or something) because a possible solution has to work with any java awt "Component" (or at least with JComponent).
    Any help very appreciated.
    Michael

    Hello,
    implement the keyListener interface for the Extended component...
    and in Keypressed method
    keyPressed(keyEvent){
    // do all ur reuirements here
    //and comsume the keyEvent...
    hope this helps

  • Dialog not on display list getting key down events

    Hi all,
    I have a listener on the stage listening for KEY_DOWN events.
    I show a dialog (MovieClip containing a TextField). Click a button
    on the dialog to close the dialog. ("close the dialog" == remove
    the MovieClip from the display list - the dialog instance is still
    around, which I think is part of the issue)
    Now, the stage's listener no longer gets KEY_DOWN events
    until I click somewhere on the stage. The dialog's text field is
    getting the key events. (I don't normally add a KEY_DOWN listener
    to this dialog, but I did as a test to see if it was indeed getting
    the events.)
    How can I get the stage to get KEY_DOWN events again without
    clicking it first? There seems to be no way to explictly set
    keyboard focus that I can find.

    Hi. What happens if you simply request focus to the
    MainTimeline? That should seem to do the trick. If focus is on a
    removed element (but it still has focus, which seems weird), the
    the stage won't get any events.
    ( 'i' before 'e', except after 'w')

  • HTML5 UI is unable to correctly get the information of  key-events .

    I have developed a plug-in for Illustrator CC2014.
    But, The Plug-in UI which was built with HTML5, is unable to correctly get the information of  key-events .
    As problems following.
        0-9 key press       : "keyCode" is "0"
        Shift key press     : "shiftKey"is "false"
        Alt key press        : "altKey"is"false"
    Even if acquired at any timing(keydown, keypress, keyup) symptom occurs.
    In the Windows, you can get the information of key-events is correct at the same implementation.
    In the case of the browser UI, even in the Mac, I can correctly get.
    What causes that can not be acquired key event information is correct on the plug-in?
    Also, If you have any way to get the information of key-events correctly, please let me know.

    Pulluran wrote:
    I tried the event, but it does not resolve.
    In the windows, onKeydownEvent(event) can get the event information correctly.
    in the Mac, the keyevent information was originally can be get.The problem is that the keyevent information was not the correct information.
    "in the Mac, the keyevent information was originally can be get"
    What does that mean?
    "The problem is that the keyevent information was not the correct information."
    The problem seems to be that the event contains no information, keyCode is always zero and shiftKey and altkey are always false.
    What happens if you try
    function onKeydownEvent(obj) {
    var keyCode = (obj.keyCode >= 96 && obj.keyCode <= 105) ? obj.keyCode - 48 : obj.keyCode;
    var inputStr = String.fromCharCode(keyCode);

  • Macbook misses some key events for a few seconds

    I have noticed that for last two months or so something strange happens to my Retina MBP. Once in a couple of days it stops responding to some key events. It is like it handles only one keypress out of 4-5. Nothing seems to be wrong with the keyboard and it is not about a particular key or keys. And about 10-15 seconds later everything goes back to normal. I do not see any suspicious messages in the logs, the computer is connected to the power supply...It happens just by itself in the middle of the day, when I am typing.
    Almost looks like some interrupts get lost by the system while it is busy with something else. But I have checked the load level and running processes - nothing interesting there....And whatever it is - it happens during a very short period of time.

    Hi,
    No, I have not returned my MBP yet. In fact, I would rather avoid doing this unless I am convinced if it is a hardware issue. And I do believe it is not. Just recently I have spent some time investigating it and I have found very stroing correlation between the moments when this happens and these messages in the kernel log:
    Jan 13 10:49:54 mbp-wifi kernel[0]: Sandbox: sandboxd(96471) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi kernel[0]: Sandbox: sandboxd(96499) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96497]): mdworker(96497) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96498]): mdworker(96498) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96503]): mdworker(96503) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96502]): mdworker(96502) deny mach-lookup com.apple.ls.boxd
    And I have also noticed that my Spotlight database gets reconstructed too often, which means it gets corrupted.
    From all this I conclude that it is most likely the software issue and it seems to be linked to spotlight. I saw people reporting similar things. So now I am researching on how to fix it without disabling the spotlight.
    In general, I believe that the quality of Apple software is going down, it is not like 4-5 years ago And Apple does seem to care less and less about it.
    If in your case it happens all the time, not just once in a while, and you see that a particular key has problems - it is possible that we are talking about the different issues and yours might be really about the keyboard.

  • KEY events in MIDlets

    Hello all,
    I am basically new to J2ME MIDP development and also new to this
    forum. So apologies if this has already been covered or turns out to
    be a stupid question :) Here goes:
    I am trying to develop a MIDlet where I have a Form to accept certain
    values from the user. This is fairly straightforward and is easy to
    create with the high level Form a and TextField objects.
    Now, I wish to add a functionality to my MIDlet, in which, the user
    can press a specific key.. say the "Select" key or the "Call" key.. at
    any time during the form to start another thread of operation which
    performs something totally different... say for example, the user is
    entering values into the form and in between somewhere he presses this
    specific key and the phone start playing music. I hope you get my
    point.
    Basically I want to listen for key pressed or key held events on a
    Form object. Now I understand that Key events can be found only on the
    low-level Canvas based UIs. So is it possible to do it with Screen class
    elements..?
    Thanks,
    Nik

    You can try to use a CustomItem. What events will be delivered to the custom item depends on the implementation, though. Also these events will be only delivered when the CustomItem is focused.
    Have a look at the J2ME Polish GUI for using CustomItems for MIDP/1.0 devices as well.
    http://www.j2mepolish.org
    Best regards,
    Robert

  • GET PERNR EVENT

    Hi experts,
    please tell me about the get pernr event and from which all tables data is fetched during the event.
    thanks,
    ajay

    Hi,
    GET is the command used in Logical database concept for fetching the data
    GET PERNR will fetch all the Pernr's one by one in a Loop like thing
    and for each pernr the data records in other infotypes have been processed
    and it goes on till all the pernr's are completed.
    see the sample code
    start-of-selection.
    Get PERNR from LDB
    get pernr.
    Get data from Respective Infotypes
    rp_provide_from_last p0001 space pnpbegda pnpendda.
    if p0001-kostl in pnpkostl.
    rep_tab-kostl = p0001-kostl.
    rep_tab-pernr = p0001-pernr.
    rep_tab-ename = p0001-ename.
    Get the Position Text
    clear t528t-plstx.
    select single plstx into t528t-plstx from t528t
    where plans = p0001-plans and
    otype = c_type and
    sprsl = sy-langu.
    if sy-subrc = 0.
    rep_tab-ptext = t528t-plstx.
    endif.
    Get the Cost Center Text
    clear cskt-ltext.
    select single ltext into cskt-ltext from cskt
    where spras = sy-langu and
    kokrs = c_kokrs and
    kostl = p0001-kostl.
    if sy-subrc = 0.
    rep_tab-ctext = cskt-ltext.
    endif.
    append rep_tab.
    clear rep_tab.
    endif.
    Regards,
    Harish

  • Something is eating my key events!

    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) {
                        System.out.println("A key was pressed");
                        backgroundpanelKeyPressed(e);
                   public void keyReleased(java.awt.event.KeyEvent e) {
                        System.out.println("A key was released");
                        backgroundpanelKeyReleased(e);
    And then the code for my key events is as follows:
         // pressing the arrow button will allow the ship to move
         public void backgroundpanelKeyPressed(java.awt.event.KeyEvent e) {
         System.out.println ("In Here!");
         switch(e.getKeyCode()) {
         case KeyEvent.VK_LEFT:
         System.out.println("Left key pressed");
         break;
         case KeyEvent.VK_DOWN:
         System.out.println("Down key pressed");     
         break;
         case KeyEvent.VK_UP:
         System.out.println("Up key pressed");     
         break;
         case KeyEvent.VK_RIGHT:
         System.out.println("Right key pressed");     
         break;
                   // releasing the arrow button will stop the ship from moving
         public void backgroundpanelKeyReleased(java.awt.event.KeyEvent e) {
         switch(e.getKeyChar()) {
         case KeyEvent.VK_LEFT:
         System.out.println("Left key released");
         break;
         case KeyEvent.VK_DOWN:
         System.out.println("Down key released");
         break;
         case KeyEvent.VK_UP:
         System.out.println("Up key released");
         break;
         case KeyEvent.VK_RIGHT:
         System.out.println("Right key released");
         break;
    I can't find the problem with any of that, but something is intercepting my key events before they even get there. Pressing the arrow keys does nothing, but if I hit the spacebar, then it calls Background's constructor.
    I searched through the entire code, and nowhere is there any key listener, or any reference to the Background class aside from where I am actually trying to call it.

    Does your program always react when you press space? Because if it didn't I'd guess you have problems with the event focus (or whatever it's called). Let's say you add your KeyListener to the Frame/Applet your game is displayed in. At some stage during gameplay a java.awt.Button is pressed. The button will keep the focus and subsequent keypresses will be reported solely to it, so your KeyListener has to listen at the button, too (or you can do a requestFocus() for the component you want to listen to, whenever it looses focus. See FocusListener on this).

  • Simulation of Key events ????

    Hello there,
    I would like to simulate a succession of pressed key events in order to trace the mem. allocations of a midlet under constant setup.
    How could I trigger those events from my application ? which low-level method should I called ?
    I tied to found myself in the API and also to 'google' for a solution, but so far it wasn't successful....
    Any idea will be welcome !
    Thanks

    Hi khsay!
    If you are using Windows as OS you can never get your application to run in realtime, you have to use LV Realtime to do that.
    If you use the event structur i a while loop you get as close as possible, i think.
    I have modified your caps.vi so it reacts on booth CAPS button and CAPS key on the keyboard.
    Hope this helps!
    Regards
    /Thomas
    Attachments:
    caps[1].vi ‏41 KB

  • Tracking changing properties during animation

    I've set up a few views in my iPhone app that I can move around using the provided animation functions. But now I want to also draw stuff on the containing view to connect objects. That works, but it does not update during animations. I have added code in the frame: method of my small views to post a setNeedsDisplay, but that only gets called at the end of the animation.
    So is there a way to observe the changes made in individual frames of an animation? Either from the animation side, or from within the views?

    Haven't found a way to do this properly, but now don't need it anymore. Key-value-observing comes close, but doesn't work for animated properties. Probably would work if I used CALayer directly.

Maybe you are looking for

  • Serial Number management In sub-contracting

    Dear Experts, A material is sent to subcontractor which is having a serial number. When I receive the material back from Subcontractor, I need to enter same serial number while posting GR. (Using 101 movement type) Unfortunately, system does not allo

  • HR Programming - Reading Infotype with PNP or straightly from tables?

    Hi there,        I was wondering what is the difference between accessing data from inftoype by using logical database PNP      GET PERNR ....   or by using      SELECT * FROM PAXXXX WHERE... Thank you for your help! Christian

  • Error Message for Heirarchical Tree

    Error : FRM-47321 Can I know more about this error message please. I get the error message when do the ftree.populate_tree. Thanks in advance Magesh

  • Home Sharing Not Working- What To Do?

    I'm trying to get home share to work but when I log in on both computers neither computer shows up on either computer. What am I suppose to do? I've done it before and it worked but now it isn't and I don't know what to do. PLEASE HELP! I need to tra

  • Siri is not responding to any question

    Siri is not responding.  latest 8.1.2 iOS.  I have started and restarted many times.  Any question whatsoever is met with the same response "sorry, i can't find that right now, please try again."   ANY question - what time is it, what is the temperat