Java Reference
In-Depth Information
The component with focus is the component that receives keyboard input.
When I first wrote the TextComponentDemo program, the text area was
given focus by default; however, I wanted the text field to have the initial
focus because that is where the user is going to type right away.
To accomplish this, I used the requestFocus() method of the Component
class. I needed to invoke this method after the Frame was displayed, so I
added a getTextField() method to the TextComponentDemo class that
allows me to invoke requestFocus() on the TextField object within main()
after invoking setVisible() on the Frame. Now, when the program is
executed, the cursor is blinking in the text field and is ready for the user
to begin typing!
The CreateList class listens to events from both buttons and the text field.
There are two ways that the following statement is true:
if(component instanceof TextField || action.equals(“Enter”))
When the source of the event is a TextField object, which will occur
when the user types in the TextField and hits the Enter key.
■■
When the action command of the component is Enter, which will occur
when the user clicks the Enter button.
■■
If the expression is true, the text from the TextField is appended to the
TextArea, and the TextField is cleared using the statement:
source.setText(“”);
Figure 13.8 shows a sample output of the TextComponentDemo program,
which displays a numbered list in the TextArea created from the text entered
in the TextField.
Figure 13.8
Output of the TextComponentDemo program.
Search WWH ::




Custom Search