简体   繁体   中英

In Java, how to take a character without pressing the enter key?

How can I get characters without pressing the Enter key?
Actually I want to build a game so I need to get characters as moves and then do the moves without the Enter key being pressed.

You could add a keyListener if your using swing example of keyListener:

public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    if(keyCode ==  KeyEvent.VK_UP)
    {
       //code here
    }
    else if(keyCode == KeyEvent.VK_DOWN)
    {
       //code here
    }
    //etc...
}

For example I am still learning keyListeners as well. but, to make a eg Rectangle move you could make a private rectangle call it in your paintComponent() rect.fillRect(0,0,10,10) then use the keyListener to check for input.

public void keyPressed(KeyEvent e){
    if (rect.getKeyCode() == KeyEvent.VK_S)

    if (rect.getKeyCode() == KeyEvent.VK_F)
        xa = 2;
    if (rect.getKeyCode() == KeyEvent.VK_E)
        ya = 2;
    if (rect.getKeyCode() == KeyEvent.VK_D)
        ya = -2;
}

EDIT: After, reading that you are not using Swing, it would help to provide some code or further expand on the details of what you want the key to do when pressed in your game.

you should take a look at:

System.in.read();

It reads the next byte of data from the input stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM