简体   繁体   中英

Create a 'BufferedReader' out of a JTextField

I'm fairly new to Java, and I need to create a 'BufferedReader' for a JTextField. What needs to happen is, when the program calls my getText() method, It needs to wait until it recieves input from the Enter key event handler. If i do something like:

String input = null;
while(true) {
  if(!input.equals(null)) {
    break;
  }
}

I get nullpointerexception errors. I've thought about it, and determined that since getText() has to return data to the method that called it, I would have to run like a nested method inside the getText() method, that would be able to run the code to run the data. Any ideas?

This is not how Swing (or just about any UI framework) works. Start by taking a look at Concurrecy in Swing for reasons why you should NEVER block the Event Dispatching Thread...

Swing is an event driven environment. The user clicks the mouse, and event is raised. The user presses a key, and event is raised.

Rather then using loops or polling, Swing utilises "listeners", which is a form of the Observer Pattern .

This allows you to attach a callback interface to an object and it will tell you when something has occured.

Take a look at Writing Event Listeners for more examples.

If you need to know when the user has pressed Enter , you should attach a ActionListener to the JTextField . It will trigger an actionPerformed event when ever the user pressed Enter

See How to write an Action Listener for more details

because, input is null.

String input = null;
if(!input.equals(null))

"null" means "It haven't initialized, or it has no value". The equals method (and every other method) requires input to not be null.

Can't call a method on a null object. Check if input is null.

if(input != null)

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