Java Reference
In-Depth Information
ton.) Based on the contents of that string, the text in the label is set to show which button
was pressed.
One last point: Remember that actionPerformed( ) is called on the event-dispatching
thread as explained earlier. It must return quickly in order to avoid slowing down the ap-
plication.
Work with JTextField
Another commonly used control is JTextField . It enables the user to enter a line of text.
JTextField inherits the abstract class JTextComponent , which is the superclass of all text
components. JTextField defines several constructors. The one we will use is shown here:
JTextField(int cols )
Here, cols specifies the width of the text field in columns. It is important to understand that
you can enter a string that is longer than the number of columns. It's just that the physical
size of the text field on the screen will be cols columns wide.
When you press ENTER when inputting into a text field, an ActionEvent is generated.
Therefore, JTextField provides the addActionListener( ) and removeActionListener( )
methods. To handle action events, you must implement the actionPerformed( ) method
defined by the ActionListener interface. The process is similar to handling action events
generated by a button, as described earlier.
Like a JButton , a JTextField has an action command string associated with it. By de-
fault, the action command is the current content of the text field. However, this default is
seldom used. Instead, you will usually set the action command to a fixed value of your own
choosing by calling the setActionCommand( ) method, shown here:
void setActionCommand(String cmd )
The string passed in cmd becomes the new action command. The text in the text field is
unaffected. Once you set the action command string, it remains the same no matter what
is entered into the text field. One reason that you might want to explicitly set the action
command is to provide a way to recognize the text field as the source of an action event.
This is especially important when another control in the same frame also generates action
events and you want to use the same event handler to process both events. Setting the ac-
tion command gives you a way to tell them apart. Also, if you don't set the action command
associated with a text field, then by happenstance the contents of the text field might match
the action command of another component.
Search WWH ::




Custom Search