2

I used to use the scanner class below to listen for input from the user through the cmd prompt but I am trying to get a Java application to listen for the text by instead using the keyTyped method.

public static void main(String[] args) throws IOException {
    new AsteroidsGame();
    InputStream inputstream = new InputStream() {

        @Override
        public int read() throws IOException {
            return 0;
        }
    };
    try {
        FileOutputStream output = new FileOutputStream("HighScore.txt",true);
        Scanner input = new Scanner(System.in);
        PrintStream printStream = new PrintStream(output);
        printStream.println(input.next() + " " + points);
        printStream.close();
        System.out.println("Success!");
    }
    catch(IOException e){
        System.out.println(e);
    }
 }

I dont know what to do to the method that will get it to listen for keystrokes and combine the letters into one word. (This is a way of getting a persons name for a game)

@Override

public void keyTyped(KeyEvent e) {      
if(lives == 0)
    {
        e.getKeyCode() = KeyEvent.???
    }
}

Any suggestions would be appreciated because the Java library and the rest of the Internet has very little to offer in terms of examples or help.

  • 1
    Key listeners/events are for Swing GUIs, not console. What is the fully qualified name of `KeyEvent`? – user1803551 Aug 11 '17 at 19:37
  • Im sorry I didnt make that clear. This is a swing GUI. Its a game called asteroids and this is my attempt at getting the users name after they are done playing. As for the name, thats my problem, I dont know what I need to put in that line that will accept someone typing their name in. – Thereisnospoon Aug 11 '17 at 19:50
  • If this is a Swing GUI you're not showing the use of any component. What are you drawing the game objects on? What component should receive the name? Why not use a normal text field? Careful with key listener, they may give you focus problems, see https://stackoverflow.com/questions/22741215/how-to-use-key-bindings-instead-of-key-listeners. – user1803551 Aug 11 '17 at 21:16
  • Look at the newest post on the bottom of this page – Thereisnospoon Aug 11 '17 at 21:41
  • This is not a forum, answers don't have an order (I can order them by votes) so newest is not always on the bottom. Any additional information goes into your question by [edit]ing it, not by posting an answer (which would get deleted as it's not an answer). – user1803551 Aug 11 '17 at 21:49
  • oops my bad. I didnt know. – Thereisnospoon Aug 11 '17 at 21:57

3 Answers3

1

If you need an ordinary listiners so you can find it in any java tutorial

If you need a custom listener, You can see here: Create a custom event in Java

Its has a goid example on custom listuners

Hasan
  • 296
  • 1
  • 8
  • 23
1

You need a subclass that extends the KeyAdapter class, this gives you access to the keyPressed method in the KeyAdapter class that you can then Override to do what you need in your program. The KeyEvent e is a parameter of the keyPressed method that has the getter getKeyCode that returns a particular int depending on the key that was pressed See simple tutorial here. So your code would simply be something like:

public class KL extends KeyAdapter {
    int k = 0;
    @Override
    public void keyPressed(KeyEvent e) {
        if (lives == 0) {
            k = e.getKeyCode();
        }
    }
}

Java has constants built in for the keyCodes so you can easily use them as required, for example the int for the left key is KeyEvent.VK_LEFT.

See more detailed explanation of this and explanation of KeyEvent listeners in chapter 6 of Eck's excellent free text

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Lew Perren
  • 1,209
  • 1
  • 10
  • 14
1

When a textual key is pressed that can be transformed into valid Unicode char it generates keyTyped event. We can catch it. Up, down etc. keys can be processed by e.getKeyCode() event types.

public class SimpleKeyListener implements KeyListener {

    StringBuilder sb = new StringBuilder();

    @Override
    public void keyTyped(KeyEvent e) {
        sb.append(e.getKeyChar());
        System.out.println(sb.toString());
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_UP) {
            System.out.println("UP");
        } else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
            System.out.println("DOWN");
        }
    }
}

Here is a hello world to test it:

public class HelloWorldSwing {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.addKeyListener(new SimpleKeyListener());

        JLabel label = new JLabel("Hello Swing");
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}