Without using Buffered Reader use arrow keys in a game.

hi guys.i am new to java and i am trying to build a 2d game in which a dot moves in all 4 directions to get to the finish...lol.
how do i get it to work without the user having to press enter after he presses the arrow keys?
pleez help!!!!!!!!!!

Hi. I am also a maker of a 2D game in which you move a ship using whatever method you choose... Here is the best way that I have found... assuming you make things "move" by repainting everything every few milliseconds...
Have 4 boolean values, upPressed, downPressed, leftPressed, and rightPressed. Now, when the user presses down the up arrow key, the upPressed variable becomes true. When he releases it, upPressed becomes false. Now, where you "move" your dot, have a method like (if upPressed==true) dot.location.y (or however you set the dot's y-location)-=15 (or however much you want it to move per frame - this may take some testing). Similarly with the others.
Now, to test if an up/down/left/right key is pressed, use a KeyEventDispatcher, like so:
public class Keyboard extends KeyAdapter implements
    KeyEventDispatcher
    public static boolean upPressed,downPressed,leftPressed,rightPressed;
    public Keyboard(){          KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
    public boolean dispatchKeyEvent(KeyEvent e)
        if(e.getID()==KeyEvent.KEY_PRESSED){
             int code=e.getKeyCode();
             if(code==KeyEvent.VK_DOWN){
                  downPressed=true;
             if(code==KeyEvent.VK_UP){
                  upPressed=true;
             if(code==KeyEvent.VK_LEFT){
                  leftPressed=true;
             if(code==KeyEvent.VK_RIGHT){
                  rightPressed=true;
        if(e.getID()==KeyEvent.KEY_RELEASED){
             int code=e.getKeyCode();
             if(code==KeyEvent.VK_DOWN){
                  downPressed=false;
             if(code==KeyEvent.VK_UP){
                  upPressed=false;
             if(code==KeyEvent.VK_LEFT){
                  leftPressed=false;
             if(code==KeyEvent.VK_RIGHT){
                  rightPressed=false;
        return false;
}Then in your main class, simply create a keyboard. (Keyboard anything = new Keyboard()). This should handle your problem. If you do not understand anything (or if it doesn't work) i will check back here later. If somebody sees an error, please tell me! I'm not very good at copy-and-pasting lol.

Similar Messages

  • How to stop record scrolling using up and down arrow key in forms

    Hi ,
    how we can restrict the record navigation using up & down arrow key...
    Thanks & Regards.
    vvm

    write key-up & key-down triggers at form level.
    inside that write the code
    BEGIN
      NULL;
    END;

  • Why can't I use the left/right arrow keys to go to the next page or back a page?

    When reading manga, I used to be able to go to the next page or go back a page using the left and right arrow keys. Doesn't work anymore, how can I fix that?

    Such a feature can only be added by an extension.
    Maybe:
    *NextPlease!: https://addons.mozilla.org/firefox/addon/nextplease/

  • Cant use arrow keys on flash games

    Hi, anyone had this problem? The arrow keys dont work when I
    play flash games. Have downloaded latest version of flash (multiple
    times) and still the same problem. I load up a flash game, then can
    only use the mouse to play. Arrow keys just dont respond when used.
    Really hope someone has had this before and knows what to do.
    Thanks for annby replies.

    To be honest the flash game must support the arrow keys to play with them. This has nothing to do with a hardware issue.
    Check the description of the game to see if you can play with the arrow keys.
    Last but not least you can try to update the flash player.

  • Controlling a projector (presentation) using left and right arrow keys

    Hello i have a cdr-rom im producing, im creating an
    interactive presentation and i would like the user to be able to
    move from page to page using the left and right arrow keys on the
    keyboard how (1) do you add the script ie, on the timeline etc (2)
    what is the exact script i need to use. Im fairly new to director
    so could you please make it as easy as possible to understand. Any
    help would be great thank you.

    You want to create a keyDown script in a movie script window.
    You can get the keycodes for the arrow keys here:
    http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_15887
    Do a search in the Lingo forum for more info on writing a
    keydown script. There are many examples to choose from.

  • Using left and right arrow keys as accesskeys

    I am trying to remediate an online course and need to apply left arrow key to next button (advance to next page) and right arrow key to back button (return to previous page). Does anyone have javascript code that would allow this?

    This is already built into major browsers.  This assumes the browser history folder contains more than one page. If the browser's history folder is empty, nothing will happen.
    For Windows users:
    Alt+Left arrow = back one page.
    Alt+Right arrow = forward one page.
    http://en.wikipedia.org/wiki/Access_key
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    http://alt-web.com/
    http://twitter.com/altweb

  • Can we silently print a PDF file programmatically without opening Adobe Reader using DDE messages

    Hi,
    Can anyone help to solve this.
    I want to silently print a PDF file without opening the Adobe reader window.
    Thanks,
    Chandu. G.

    I would like to do that same thing.  Did you ever find an answer to this question?

  • Findind out the number of lines within a string - using buffered reader

    Hi All,
    Want to know the number of lines within a string..Sample code is there for reference..could u help me out how to have the number of lines in a string without java comments (i.e string within /**------*/ and // should be eliminated)
    public class ReadLines {
         public static void main(String[] args) throws Exception{
              ReadLines rl = new ReadLines();
              rl.readLines();
         void readLines() throws Exception{
              String str = "/** This is a test message\n"+
                   "* for testing\n"+
                   "*/\n"+
                   "import java.io.*\n"+
                   "// this is again comment\n"+
                   "public class ReadLines {\n"+
              BufferedReader reader = new BufferedReader(new StringReader(str));
              String line = "";
              int count = 0;
              while ((line = reader.readLine())!= null )
                   //line = reader.readLine();
                   count++;
              System.out.println(count);
    }Thanks
    MK

    Hi
    What you need to do is parse the file in such a way that you read /*, */ and // as tokens. By that I mean rather than read a line at a time (although I'm sure you could), read it character by character. So every time you reach a new line character then increment the counter. But there are two casaes when you don increment the counter they are:
    If you encounter a / followed by * then keep reading but if you encounter a newline character then DONT increment the counter ONLY continue counting when you read a * followed by a / (as this is the end of the comment)
    If you encounter / followed by another / then do not count that particular line and go to the next line and continue counting from there.
    Where I've written 'continue counting' this is subject to the lines that follow not conforming to the above two cases.
    I hope this helps.

  • Key Bindings using the arrow keys

    Following is some code that allows you to move a component around the screen using the arrow keys. I've noticed a problem and I'm just wondering if its Java or my keyboard.
    Lets start with an example that works:
    Press the down and right keys. Then press either the up or left key. The image moves proving that it supports 3 keys.
    Now for the problem:
    Press the up and left keys. Then press either the down or right key. Three things to notice:
    a) the direction doesn't change when the third key is pressed
    b) no output is displayed, so the ActionListener is not being invoked
    c) after a short time, the program starts beeping
    Now try rerunning the code after removing the comments that assign the key bindings to the "a, s, d, f" keys. Redo the above test and it works even if all four keys are pressed.
    I don't remember this problem when I wrote the code a while ago, but I did recently get a cheap new keyboard so I'm just wondering if the problem is my keyboard or whether its a quirk with Java.
    You can download Duke from here:
    http://java.sun.com/docs/books/tutorial/uiswing/examples/components/LayeredPaneDemoProject/src/components/images/dukeWaveRed.gif
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyboardNavigationProblem implements ActionListener
         private JComponent component;
         private int deltaX;
         private int deltaY;
         private Timer timer;
         private int keysPressed;
         private InputMap inputMap;
         public KeyboardNavigationProblem(JComponent component, int delay)
              this.component = component;
              this.deltaX = deltaX;
              this.deltaY = deltaY;
              timer = new Timer(delay, this);
              timer.setInitialDelay( 0 );
              inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
         public void addAction(int keyCode, String description, int deltaX, int deltaY)
              new NavigationAction(keyCode, description, deltaX, deltaY);
         public void updateDeltaX(int delta)
              deltaX += delta;
         public void updateDeltaY(int delta)
              deltaY += delta;
         public void actionPerformed(ActionEvent e)
              int componentWidth = component.getSize().width;
              int componentHeight = component.getSize().height;
              Dimension parentSize = component.getParent().getSize();
              int parentWidth  = parentSize.width;
              int parentHeight = parentSize.height;
              //  Determine next X position
              int nextX = Math.max(component.getLocation().x + deltaX, 0);
              if ( nextX + componentWidth > parentWidth)
                   nextX = parentWidth - componentWidth;
              //  Determine next Y position
              int nextY = Math.max(component.getLocation().y + deltaY, 0);
              if ( nextY + componentHeight > parentHeight)
                   nextY = parentHeight - componentHeight;
              //  Move the component
              component.setLocation(nextX, nextY);
         class NavigationAction extends AbstractAction implements ActionListener
              private int deltaX;
              private int deltaY;
              private KeyStroke pressedKeyStroke;
              private boolean listeningForKeyPressed;
              public NavigationAction(int keyCode, String description, int deltaX, int deltaY)
                   super(description);
                   this.deltaX = deltaX;
                   this.deltaY = deltaY;
                   pressedKeyStroke = KeyStroke.getKeyStroke(keyCode, 0, false);
                   KeyStroke releasedKeyStroke = KeyStroke.getKeyStroke(keyCode, 0, true);
                   inputMap.put(pressedKeyStroke, getValue(Action.NAME));
                   inputMap.put(releasedKeyStroke, getValue(Action.NAME));
                   component.getActionMap().put(getValue(Action.NAME), this);
                   listeningForKeyPressed = true;
              public void actionPerformed(ActionEvent e)
                   if (listeningForKeyPressed)
                        updateDeltaX( deltaX );
                        updateDeltaY( deltaY );
                        inputMap.remove(pressedKeyStroke);
                        listeningForKeyPressed = false;
                           if (keysPressed == 0)
                                timer.start();
                     keysPressed++;
                   else // listening for key released
                        updateDeltaX( -deltaX );
                        updateDeltaY( -deltaY );
                        inputMap.put(pressedKeyStroke, getValue(Action.NAME));
                        listeningForKeyPressed = true;
                        keysPressed--;
                           if (keysPressed == 0)
                                timer.stop();
                   System.out.println(KeyboardNavigationProblem.this.deltaX + " : "
                   + KeyboardNavigationProblem.this.deltaY);
         public static void main(String[] args)
              JPanel contentPane = new JPanel();
              contentPane.setLayout( null );
              JLabel duke = new JLabel( new ImageIcon("dukewavered.gif") );
              duke.setSize( duke.getPreferredSize() );
              duke.setLocation(100, 100);
              contentPane.add( duke );
              KeyboardNavigationProblem navigation = new KeyboardNavigationProblem(duke, 100);
              navigation.addAction(KeyEvent.VK_LEFT, "zLeft", -5, 0);
              navigation.addAction(KeyEvent.VK_RIGHT, "zRight", 5, 0);
              navigation.addAction(KeyEvent.VK_UP, "zUp", 0, -5);
              navigation.addAction(KeyEvent.VK_DOWN, "zDown", 0, 5);
    //          navigation.addAction(KeyEvent.VK_A, "zLeft", -5, 0);
    //          navigation.addAction(KeyEvent.VK_S, "zRight", 5, 0);
    //          navigation.addAction(KeyEvent.VK_D, "zUp", 0, -5);
    //          navigation.addAction(KeyEvent.VK_F, "zDown", 0, 5);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.setContentPane( contentPane);
              frame.setSize(800, 600);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

    if you hold down left and right (so it doesn't move), down works, but not up.
    hold up/down, right works but not left.Yes, the problem only seems to be when the up and left in combination with the right or down key is pressed.
    num lock off - use the number pad arrow keys and all works OK Thats interesting, I didn't notice that. Although it just confuses the issue as to what the problem is.
    So it appears to me that:
    a) left + up + down, and
    b) left + up + right
    are special key combinations that are intercepted by either the OS or the JVM. Do these key combinations ring a bell to anybody?
    I'm use JDK1.4.2 on XP. I wonder if other OS will have the same problem?
    Again, this isn't a real, problem, just more of a curiosity. Thanks,

  • Bridge CC crashes while using arrow keys to switch images

    Adobe Photoshop CC 2014 Adobe Bridge 2014 on Mac is crashing every time I press an arrow key to move through images in bridge. I can click to manually select images with no problem, but using the up/down arrow keys to move to the next image up/down brings up the spinning beach ball and immediately locks the program up, requiring a force quit.
    Did the usual Mac permissions and fsck stuff to no avail. Ideas?
    Dan

    Thanks for moving my post to this correct forum. (I'm afraid I missed it when I originally posted.) A bit more information based on attempts to fix and on further attempts to use the program.
    After launching Bridge — before I select any specific image — it initially seems to work correctly. For example, I can use menu items and select and open folders. However...
    Once I drill down through folders to show raw files in the browser the problems begin. I can manually select an image by clicking on it, but the program the locks up if I do things such as attempt to navigate to another image using the up/down keyboard arrows or select anything from a menu that would perform an action on the image. (The problem happens with any image selected — not one particular image, and with images that worked fine until 48 hours ago.)
    ACR still works. I can double click an image and open the raw converter, and I can doubly click a smart object image in Photoshop do go back to the raw editor and it allows me to edit.
    I did the step of holding down command-option-shift at Bridge startup and selecting all three options to delete the cache and so forth. Still no joy.
    I did the usual Mac disk/file system repair stuff — repairing permissions and repairing disk — to no avail.
    I downloaded and reinstalled Bridge but the problem persists.
    Since I have a full backup of the drive on which Bridge is installed and since this backup drive is bootable, I double clicked the copy of Bridge on the backup drive... and it opened (slowly!) but worked correctly. (Not that this means much, but my second instance on my laptop continues to run fine.)
    I'm stuck, in a serious way, at this point. Thoughts?
    Thanks,
    Dan

  • Why do arrow keys stop working with type in CS6

    I searched this issue and found many forums discussing the topic, but no solution. When using PS CS6, the arrow keys randomly stop working when navigating around in text. This is extremely frustrating. Per other discussions, and my experience, there doesn't seem to be a constant trigger. Saving the PS file when it happens SEEMS to fix it - at least temporarily. It's been happening off and on since I upgraded.
    Adobe reps (they're say "employee") monitoring the photoshop.com forums suggested the fix is to close all other apps. No one works that way. Chrome (or other browsers) were speculated to be the cause. but I just had this happen without any browser open.
    Any insight would be greatly appreciated. It's the simple things that cause the most frustration.
    Sysytem details:
    CS6 upgrade form CS5 Premium
    Lion 10.7.4 / 16G / i7 Intel
    Safari / Chrome
    MS Office
    Mac Mail
    FontAgent Pro

    Nobody suggested that closing other apps was fix - that was just a test to determine which apps were causing problems with event handling that prevented Photoshop from correctly handling the key events.
    And if there were already posts on this topic, why did you create a new topic on the same thing?

  • Bug? Can change swatches with arrow keys?

    I use the Live Paint option and the Live Paint bucket often.  It is really convenient to change the swatch I am using by using the left-right arrow keys to change my swatch chosen in the Swatch Palette.  But in CS6, if I am doing so, and the next swatch chosen is a percentage tint of another color (for example, I have a swatch Blue, and a swatch Blue 85%, which is the Blue Swatch tinited to 85% in the color palette and then made into a saved swatch), the "select" box around the swatch disappears, and I can no longer change the swatch choice without re-clicking on it.
    I can change easily between swatches that are not percentages of the original, with no problem.  CS5 and all earlier versions that had this feature had no problem whatsoever.
    Huh????

    All swatches are CMYK creations by me, then I choose Global.  So, I get swatches called things like, Skin Dark, Skin Med, Skin Light.  Then, I want something a tint of one of these. So in the color Palette with a Swatch chosen, I slide tint to say 50%. Then I make a new swatch ("Skin Light 50%", global). Using the arrow keys, when I get to this new % swatch, it deselects, and I can't "scroll" through the swatches, as the "white outline" selection disappears and the swatch selection stays on this % swatch.

  • Alternative to arrow keys to move 1 frame left or right in timeline/viewer

    Other than punching in different timecode values, are there any other keyboard or button shortcuts that will move the timeline or viewer playhead 1 frame backwards or forwards WITHOUT using the left/right arrow keys?

    That's a handy tip Andy, though I don't know whether it's any quicker than the arrow keys as you have to position the cursor in the playhead track of the timeline.
    On a Logitech mouse it was perfect but the wheel on my Mighty Mouse is much too sensitive and fiddly to make it a pleasurable experience.

  • In Dreamweaver CC code view, how do I reenable shift-control+arrow keys to select words?

    In previous versions of Dreamweaver (for Windows but presumably for other operating systems as well) and in pretty much any other text editor (except maybe for vi/m but including the one I'm using to write this message in now). I can select characters using shift plus the arrow keys and select words by pressing shift-control plus the arrow keys. It seems you now have to use shift-alt to select words. I don't want to have to undo about 25 years of habit just for Dreamweaver.
    Please say this is an easy setting I can uncheck somewhere! Thanks!

    That is an issue that has come up a lot lately...
    Make sure to add your voice to the others here: https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform and hopefully in the next release they'll put it back to normal.

  • CS6 Bridge, Arrow keys are slow

    I'm on a Mac Pro, quad core, 9 GB memory. I have been using CS5 for all my photo work and use Bridge and ACR to do all of my editing. I have set up two monitors with content on the right screen as thumbnails and preview (and other tabs) on the left screen. To do my edits I use the right/left arrow keys to scroll through the images (and then make my picks/ratings) as I go.
    I just installed CS6 Demo and am trying to do the same thing...everything else works normally but the right/left arrow keys (moving from image to image) now takes 4 to 5 seconds to bring up the image (CS5 was instant).
    All paramaters/settings/preferences are the same. I know CS6 needs a more powerful video card (mine is only 256 mb...I will be upgrading soon)...but here's the weird thing which leads me to believe that's not the problem...the up and down arrow keys work normally, i.e. they go from image to image instantly. I edit folders of images that range from 200 to 300, up to 1500 images from a shoot on a daily basis so I need this to work for me! Any suggestions/ideas?
    Also, I'm having problems trying to run a batch in CS6, I set up an action identical to what I had running in CS5 (embedding a text logo on an image) and while it goes through the process of doing the action, at the end it pops up an error message and lists all the images saying it could not process the request. Weird or what?

    Not really.  Mine is instant, have a low to med qual. video card with 1 gig Vram.
    Not sure why up and down is different than right to left, but always possible different sub routine.

Maybe you are looking for

  • Set Password for VIs Programmatically

    Hi Experts, I would like to create a VI for setting passwords to my VIs. My VIs are palced in llbs... That's peace of cake, but I want to save the VI too in order to password-protection take effect. I found a property node, "save for previous version

  • Outlook 2010 won't update new messages unless you update folder

    Hi, Outlook 2010 sp1 with Exchange 2010 latest sp. Scenario: Some users are not receiving emails unless they click on update Folder. Once they do emails come in. Troubleshooting: No virus scanning outlook folder. Delete the profile with OST and re-cr

  • BAM cannot connect to WEBLOGIC

    I have this setup in my EMS : WeblogicJMS View|Edit|Copy|Delete|Create|Start|Stop|Test|Refresh Name: WeblogicJMS Owner: fmwadmin Created: 7/29/08 3:00:57 PM Last modified: 7/30/08 6:34:52 PM Status: Stopped Initial Context Factory: weblogic.jni.WLIni

  • Innventory Transfer

    Hi All, In Inventory transfer , on line level there are two prices , Info Price and Item Cost. Which is to be taken ? apart from this , none of the costs reflect in audit report ? Please explain this. Help required urgent. thanking you Malhaar

  • Air-cap3602i-a-k9 white led

    Installing 27 of these at one location and have found one that will not boot. When you console into it and reboot the AP there is no console info.