Buttons and Labels
We’ll start with the simplest components: buttons and
labels. Frankly, there isn’t much to say about them. If you’ve seen one
button, you’ve seen them all, and you’ve already seen buttons in the
applications in Chapter 2 (HelloJava3 and HelloJava4). A button generates an ActionEvent when the user presses it. To receive
these events, your program registers an ActionListener, which must implement the
actionPerformed() method. The argument
passed to actionPerformed() is the
event itself.
There’s one more thing worth saying about buttons, which applies to
any component that generates an action event. Java lets us specify an
“action command” string for buttons (and other components, like menu
items, that can generate action events). The action command is less
interesting than it sounds. It is just a String that serves to identify the component
that sent the event. By default, the action command of a JButton is the same as
its label; it is included in action events so that you could use it to
figure out which button an event came from. However, you’ll often know
this from the context of your event listener.
To get the action command from an action event, call the event’s
getActionCommand()
method. The following code checks whether the user pressed the button
labeled Yes:
publicvoidactionPerformed(ActionEvente){if(e.getActionCommand().equals("Yes"){//the user pressed "Yes"; do something...}}
Yes is a string, not a command per se. You can change the action ...