简体   繁体   中英

KeyBinding for getting text from JTextField

I have a JTextField that will hold the user's input before they submit it (like a console Scanner object if you will). My main class has a method for getting input from the user. With a Scanner object this was easy to do: scannerObject.nextLine() . With this JTextField , I decided to use Key Bindings to determine when the Enter key was pressed in order to "submit" the contents of the JTextField . I set up the Key Bindings no problem, but I can't figure out how to get the main program to wait until the Enter key is pressed to look for the text. If I use a loop, the program gets stuck and cannot register the key press.

Here is a method that tries to get the input from the JTextField :

public static String getStrInput() {
    // Request input
    display.print(">> ");
    needInput = true;
    nextInput = "";

    // Wait until a string is input from the text field
    while (nextInput.isEmpty());    // Wait

    needInput = false;

    return nextInput;
}

And here is the Event Handler for when the Enter key is pressed in my Key Binding class:

private class SubmitAction extends AbstractAction implements ActionListener {
    /**
     * Makes Java happy.
     */
    private static final long serialVersionUID = 1L;

    /* -- Constructor -- */
    public SubmitAction() {
    }

    /* -- Method -- */

    @Override
    public void actionPerformed(ActionEvent e) {
        if (Game.needInput())
            Game.submitTextField();
    }
}

Note: All the submitTextField() method does is call the textField.getText() method and set the nextInput field (see my first method) to the returned String.

What is supposed to happen is the request for input should be registered (this is the needInput = true line), and the Key Binding class should then submit the text field when the Enter key is pressed (since the Game.needInput() condition now returns true). However, in my getStrInput() method, the program gets stuck in the while (nextInput.isEmpty()); loop. I figured that this would happen, but I have no clue how to get the main program to wait until the Key Binding's event handler has the text field submit its contents.

If this makes no sense at all or I need to reveal more code, I will happily elaborate. I've spent all day working on this little problem just to find frustration.

With this JTextField, I decided to use Key Bindings to determine when the Enter key was pressed in order to "submit" the contents of the JTextField.

Actually you should just be adding an ActionListener to the text field. The ActionListener will be invoked when the Enter key is pressed.

If you want to prompt and wait for text to be entered, then you should be using a JOptionPane .

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