Lag on key press (key event)

Hello, I am currently working on a simple game in Java. I've used Java's Key_Pressed in Key Event to control a ship moving back and forth with the up and down keys. I've noticed that when a key is pressed there is a short pause before the ship actually moves. What can I do to avoid this pause?

The "repeat rate" for holding a key down is controlled by the OS.
You should not be relying on multiple KeyEvents to move your component as the repeat rate will vary from machine to machine. Actually you should not be using KeyEvents anyway you should be using [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]Key Bindings
On keyPressed binding you would start a Timer and then on keyReleased you stop the Timer. You can then control the interval at which the Timer fires so you game will be consistent on all machines.

Similar Messages

  • Surprising behaviour ..key pressed key event

    Hello,
    I am experiencing a supprising event key press issue. I have written below code in which my code getting called even though I didnt press any of the key,
    _entryPane.getTextArea().addKeyListener(new KeyAdapter() {
                 public void keyPressed(KeyEvent e) {             
                           doSendTypeStatus();
                     if(e.getKeyChar()==KeyEvent.VK_ENTER) {
                        if(e.isControlDown()) {As shown above , doSendTypeStatus() function getting called automatically ,i.e. with out being pressed any of the key on key board .
    Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 82 in LivehelpTextEntryPanel$1))     
         LivehelpTextEntryPanel$1.keyPressed(KeyEvent) line: 82     
         TextAreaPane$MyTextArea(Component).processKeyEvent(KeyEvent) line: 5058     
         TextAreaPane$MyTextArea(JComponent).processKeyEvent(KeyEvent) line: 2388     
         TextAreaPane$MyTextArea(Component).processEvent(AWTEvent) line: 4909     
         TextAreaPane$MyTextArea(Container).processEvent(AWTEvent) line: 1569     
         TextAreaPane$MyTextArea(Component).dispatchEventImpl(AWTEvent) line: 3615     
         TextAreaPane$MyTextArea(Container).dispatchEventImpl(AWTEvent) line: 1627     
         TextAreaPane$MyTextArea(Component).dispatchEvent(AWTEvent) line: 3477     
         DefaultKeyboardFocusManager(KeyboardFocusManager).redispatchEvent(Component, AWTEvent) line: 1713     
         DefaultKeyboardFocusManager.dispatchKeyEvent(KeyEvent) line: 627     
         DefaultKeyboardFocusManager.preDispatchKeyEvent(KeyEvent) line: 831     
         DefaultKeyboardFocusManager.typeAheadAssertions(Component, AWTEvent) line: 741     
         DefaultKeyboardFocusManager.dispatchEvent(AWTEvent) line: 592     
         AgentFrame(Component).dispatchEventImpl(AWTEvent) line: 3506     
         AgentFrame(Container).dispatchEventImpl(AWTEvent) line: 1627     
         AgentFrame(Window).dispatchEventImpl(AWTEvent) line: 1606     
         AgentFrame(Component).dispatchEvent(AWTEvent) line: 3477     
         EventQueue.dispatchEvent(AWTEvent) line: 456     
         EventDispatchThread.pumpOneEventForHierarchy(int, Component) line: 201     
         EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 151     
         EventDispatchThread.pumpEvents(int, Conditional) line: 145     
         EventDispatchThread.pumpEvents(Conditional) line: 137     
         EventDispatchThread.run() line: 100     can any one please help me in resolving this issue. I am implementing typing status feature in my chat application. but due to this key event behavior , my implementation is failing completely.
    Looking for reply.
    thanks in advance
    Ani

    What is the question?
    doSendTypeStatus() function getting called automatically ,i.e. with out being pressed any of the key on key board .No, it is getting called whenever a key is pressed in the text area. It can be any key, but a key must be pressed. If you claim not to be pressing any keys, please print out the event.
    // wrong:
    if(e.getKeyChar()==KeyEvent.VK_ENTER) {
    // right:
    if(e.getKeyCode()==KeyEvent.VK_ENTER) {You should compare codes with codes, not chars
    Lastly you might want to use a document listener instead, so you also get notified when the user pastes something in the text area.

  • Key pressed event

    I need message to be displayed when certain key pressed. Why it's not working?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestKey extends JPanel implements KeyListener {
         public TestKey(){
              addKeyListener(this);
         public static void main(String arg[]){
               JFrame frame = new JFrame();
                  frame.setTitle("Test my keybord, man!");
                  frame.setSize(300, 200);
                  frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                      System.exit(0);
                  Container contentPane = frame.getContentPane();
                  contentPane.add(new TestKey());
                  frame.setVisible(true);
         public void keyPressed(KeyEvent ke){
              System.out.println("key pressed");
         public void keyTyped(KeyEvent ke){
              System.out.println("key typed");
         public void keyReleased(KeyEvent ke){
              System.out.println("key released");
    }

      public TestKey(){
        setFocusable(true);//<----------
        addKeyListener(this);
      }

  • How to change a h:outputText value in the current form on key pressed event

    Hello Suners,
    Greetings! I'm developing my first JSF web application and i'm trying to figure a way out to change outputText value when key pressed on another inputText so that when the user is typing his name for example he can see the letters showing respectively in the outputText.
    I managed to do it onchange but the user must focus out of the inputText to see his name in the outputText which is not right and the form must submit onchange event which is annoying.
    <h:inputText value="#{login.username}" title="name" id="name" required="true" onchange="this.form.submit()" >
                                <f:validateLength maximum="10" minimum="1"/>
                                <f:validator validatorId="myValidator"/>
                                <f:valueChangeListener type="classes.MyListener"/>
    </h:inputText>Is there any listener i can associate with the "onkeypress" attribute? Can anyone help me to do that with JSF?
    King Regards,

    hi, with JSF 2 you got the ajax tag, just tried it and it works fine :)
    <h:inputText id="myinput" value="#{back.name}">
        <f:ajax execute="@this" event="keyup" render="outtext"/>
    </h:inputText>
    <h:outputText id="outtext" value="#{back.name}"/>or before JSF 2
    <h:outputScript name="jsf.js" library="javax.faces" target="head"/>
    <h:inputText id="myinput" value="#{back.name}" onkeyup="jsf.ajax.request(this, event, {render: 'outtext'}); return false;"/>
    <h:outputText id="outtext" value="#{back.name}"/>The name property is a simple String in the bean.
    Hope this helps
    Edited by: hereps on Aug 21, 2010 7:18 AM

  • Catching Alt Key Press with the Key Down Filter Event

    I am writing an application that requires specific key combinations using ctrl, shift, and alt in addition to a function key (F1, F2, F3, etc).  The application works great except for when I try to catch an alt key press.  The alt key press does not seem to fire an event eventhough it is an option in the PlatMods cluster as well as the VKey enum.  When I press the alt key when my application is running the cursor changes to a normal mouse pointer from the usual finger pointer and prevents any other key presses from going through (in addition to not firing an event itself).
    I have tried completely removing the run-time menu, which doesn't seem to help.  I currently discard all keys after I handle them in my event structure.
    I really hope that the only solution isn't using a Windows DLL.  Any suggestions or ideas at all would be greatly appreciated.
    Thanks,
    Ames

     Hi Ames
    As Kileen has said Khalid has already given you a good solution to detect the ALT key.
    I have another approach that might let you stick to your event-driven approach. I suggest that you have another loop in your app that polls the keyboard using the Input Device utility vi's. When this poll loop sees an ALT + KEY combo it raises a dynamic user event and will be processed in your event structure. This means you can keep your key down filter event to process the CTRL + KEY and SHIFT + KEY events.
    Example attached in 7.1
    cheers
    David
    Attachments:
    Catching Alt Key Press Poll with Events(151551).vi ‏89 KB

  • Capturing Key press when the focus is not on VI. (event is not working).

    I have a VI, and found similar in Forums. I need to catch key down event, when the focus is not on VI.
    I attached the VI found in forum. Try to click on other window, for example on block diagram of VI, when VI is running and check if it works. The answer is no, it doesn't work. When you press any key, the led button must change it's state, but it does only when the focus is on VI's front panel. The question is how to control key press, when VI is minimized or inactive. Is it possible to catch key down or any similar event, when the focus is on any other application, not on VI?
    Solved!
    Go to Solution.
    Attachments:
    simulatekeyevent.vi ‏16 KB

    Have a look at the "Connectivity...input devices..." menu.
    For an example, open the example finder and look for "basic input demo". It should give you some ideas. Good luck!
    LabVIEW Champion . Do more with less code and in less time .

  • Question about generate key press event to system. help plz.

    I am wondering if it is possible to write a java program to generate key press event(not receiving)to the local system so all the other program in the system receive those key press event also. Thanks.

    Hi,
    :. I don't know what exactly you intend to accomplish. But, I have used the following code in order to simulate keys pressing inside a Java application.
          /* - - - Simulates TAB (java.awt.Event)
          EventQueue evtq = Toolkit.getDefaultToolkit().getSystemEventQueue();
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          /* - - - Simulates Shift+TAB (java.awt.Event)
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );:. However, as far as I know to send keys to the whole OS you have to create a 'Hook' as described inside Win32API documentation. That's for Microsoft Windows naturaly.
    Cheers.
    Roque

  • Key Press Event

    I have been pouring through the TLF API docs looking for
    events to handle key presses on a TextFlow and I am not finding
    anything. I'm sure it's simple, can anyone give me a clue? I'm
    looking to detect Ctrl+B, Ctrl+I, etc.. to trigger formatting.

    The events go to the DisplayObjectContainerController. You
    will want to override the processKey event functions to add special
    handling. Those are in the protected methods section and are
    inherited from a base class.

  • Unable to receive Tab key press event

    Hello,
    I have written a component which extends JComponent.
    For that , when Tab key is pressed I need to process something.
    I have overridden the function processKeyBinding in my class.
    But I am not getting any event for tab key press. For all the other key press events, the function is being called.
    I also tried to create a action and add it to the action map. But that is also not working.
    Can anyone explain me why it is not working and give me the solution.
    Thanks in advance,
    Anu

    public static void removeTabFromFocusTraverval(Component c) {
         int id = KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS;
         Set strokes = c.getFocusTraversalKeys(id);
         Set newStrokes = new HashSet(strokes);
         newStrokes.remove(KeyStroke.getKeyStroke("TAB"));
         c.setFocusTraversalKeys(id, newStrokes);
    }

  • Detect Key Press and Mouse Motion in ONE event?

    Hi
    I am trying to create a functionality where a mouse motion from left to right performs one action, and the same motion while a given key is pressed performs another action.
    How can i combine the two events? How do I unify the KeyEvent and MouseEvent, particulary when I need to capture the directional motion of the mouse together with the key press?
    many thanks for any insight

    you cannot actualy combine them into 1 event but there is an easy way around this:boolean mouseKeyPressed = false;
    public void keyPressed (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or e.isCtrlDown(), e.isAltDown(), ...
        mouseKeyPressed = true;
    public void keyReleased (KeyEvent e)
      if (e.getKeyCode () == ??) \\ or !e.isCtrlDown(), !e.isAltDown(), ...
        mouseKeyPressed = false;
    public void mouseMoved (MouseEvent e)
      if (mouseKeyPressed)
        //processAction
    }hope this helps,
    greetz,
    Stijn

  • How to binding a key press event of "Esc" to "cancle" button

    I create a class extended JComponent. Than I add a button named "cancle " to it.
    Than I add the class's instance to a JDialog object.
    I try to get the key press event through add a keyListener to the class instance, but no works.
    I try to add a keymap and action map to the dialog 's getRootPane() also no works.
    Who can tell me how can I do?

    Thats the way I did it:
        // map escape key
        ActionListener escapeActionListener = new ActionListener()
          public void actionPerformed(ActionEvent e)
            cancelPressed();
        this.registerKeyboardAction( escapeActionListener,
                                     KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false),
                                     JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );

  • What to use for the events of 2 keys pressed simultaneously?

    Question:
    What to use for the events of 2 keys pressed simultaneously? As the key listener has limited functionality, in this case, I need something that can act to two events (see below)
    Goal
    1. A user presses right and up at the same time
    2. Program responds to this event changing BOTH the vertical and horizontal speeds of the player
    Problem
    I currently have a key listener to do this, using key pressed, however, it only acts to up OR right at one point in time. So the user can only increase his or her vertical speed; or horizontal speed at one point in time. Instead of increasing them both.
    Example
    Here is an example of the game: http://www.kongregate.com/games/MINDistortion/bubbles-2

    DarrylBurke wrote:
    I don't know whether there's a better way (or whether this will work as expected), but I would try setting a boolean flag on keyPressed and reset the flag on keyReleased, for each key of interest. To compute the x / y movements, I would check the state of all flags.
    dbI was thinking about your answer a few nights ago. And I was like, wait... it works! I thought, at first (as I replied before) that it wouldn't work, but I refract what I said. Its actually a very simple solution. And I apologize for questioning your solution previously. Thanks so much!
    P.S. I tested it out. Works like a charm.
    -Create booleans to handle each key
    -Set to true on press
    -Set to false on release
    -Check and update in separate thread accordingly

  • Raise Key pressed event

    Hello, any know how can I raise a key press event throw code. For example I want to simulate that the user has press the A Key. How can I do that throw code?
    Thanks a lot !!

    Hi there,
    Your question has been discussed previously in the forums. Sounds like you want to programmatically click a button in WPF.
    Please check out this post
    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1329603&SiteID=1
    Thanks,
    Jennifer

  • To trigger event or action on "TAB" key press on web dynpro view

    Hi, I need to trigger event on "TAB" key press on web dynpro view , is it possible?How?

    Hi Dipak
    What Madhu said is correct. Tab key is pre-configured to move cursor from 1 field to next field. we can not create an event on tab key press.
    Regards
    Gaurav

  • How to detect space key pressed event

    I am working on a japplet where it is needed to pause the applet on the occurrence of a space bar key pressed event can anybody help
    thanks in advance

    Have a look at the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    -Puce

Maybe you are looking for

  • Pages '09 integrating straight and curly quotes within one file.

    I'm doing an edit in Pages and the document has a mix of straight and curly quotes. I can't seem to find a way to get them all the same. Find-and-replace turns some of the quotes backwards (as in 'em for them) Nothing in the archives addresses this.

  • How do I change the default PDF viewer on my iPad so I can easily see annotations?

    I keeping missing annotations on PDF because the built-in iPad Mail viewer does not show annotations.  To limit the keystrokes, instead of  using "open with" on each PDF email attachment to view in a third part app, I'd like to just change the mail d

  • Changing Apple ID in iPhone for Photo Stream

    How can I change my Apple ID in my iPhone for everything.. Not just for iTunes. When I use my iPhone anything related to Photo Stream it asks me with my old Apple ID. I've changed it and it worked for everything except for Photo stream

  • Strange HTTP probe with .cfm files.

    Hey All, I setup an http probe that checks a .cfm page for a keyword. according to the documentation there needs to be a content-length in the header for this to be parsed correctly. For some reason this .cfm page does not send the content-length. Th

  • Content Search Webpart Query (urltoken to list metadata column)

    Im developing a internet site using Cross site publishing. In the publishing site collection, on a category page, Im trying to query the relevant contents on a catalog list using urltoken to metadata column on a list using Content search webpart. I h