My first attempt at using the key binding involved attaching the binding to the component most affected by it: the JTextArea called comm. It's where the user will type the commands. When the user presses the ENTER button on the keyboard, I want the program to take what the user has typed and submit it to a method that will check the text for keywords. However, when the binding code is attached to comm, the program only recognizes the button press when that component is in focus. If the user has clicked elsewhere on the window before pressing ENTER, nothing will happen. I need to attach the code to the entire window instead of just that component, so that the event will trigger whenever the ENTER button is pressed, not just when that one component is in focus. Granted, it will be rare for the user to press ENTER after selecting a different component, but I want to cover those rare instances. Especially if I ever want to add timed events to this project, or future projects that use this same engine. I don't need the user feeling added frustration at failing a timed event because the comm component accidentally lost focus before he or she could press ENTER. As it turns out, all I have to do to accomplish this attach the binding to the view component as well. The code ends up looking like this:
comm.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "inputComm"); comm.getActionMap().put("inputComm", inputComm); view.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "inputComm"); view.getActionMap().put("inputComm", inputComm);
Now, not matter where you click in the window, the program recognizes when you press the ENTER button. Next step is to take whatever the user has typed into the text area, pass it to a method that will check it against available commands, and clear the text area so it is ready to have another command typed into it. Also, I think I am going to add in the functionality of letting the user instantly retype the last command entered by pressing the down button, like DOS used to. Just in case you wanted to do the same thing again, or if you typed something wrong and wanted to try that command again after correcting the error without having to retype the entire thing. This requires another global String variable called lastComm.
Next time, we examine the method that looks at the commands the user give the program!