Java Reference
In-Depth Information
Note that the constructor takes a String argument—that's the text that
will appear in the button. A button may also have an icon (image) in it (more
on that in just a bit). These buttons, as created, don't do anything. When
clicked on by the user, they will behave as real buttons (depress, then release),
but no action will occur. Yet.
16.7.2.5
We need to attach an action to each button, which is little more than a special
class to hold the code that you want to be run when the button is pressed. We
can define the action as an anonymous inner class, so that the code is right
there, inline with the rest of our code. Then we just attach that code to the
button. Here is an example of that for our close button (the one labeled Quit ):
Actions for Buttons
234 ActionListener closAction = new ActionListener()
235 {
236 public void
237 actionPerformed(ActionEvent e)
238 {
239 System.exit(0);
240 }
241 } ;
ActionListener is an interface—a very simple interface that defines just
one method, actionPerformed() . You can take any class, have it extend
ActionListener , and then define an actionPerformed() method for it.
That class can then serve as the action for a button. Here we just create an in-
line class that does nothing but the actionPerformed() method, and a pretty
simple one at that. It simply exits.
We could define the action elsewhere, and then just use the reference to
the action. If we had put the declaration of closAction at a higher lexical
scope (out at the beginning of the class definition, for example) then other UI
elements could also use this action. Of course, if you're going to share your
action between GUI elements, be sure that you write the code to be reentrant.
Lines 244-267 (still within the createButtons() method) define the
action for the button labeled New Subaccount . Line 268 connects it to the
button. Don't pay attention to the specifics of this action just yet. We'll discuss
it in detail below, once we know more about the other objects. Here is how
that action is built:
Search WWH ::




Custom Search