Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^413


Scenarios:What happens when the application begins? The user interface card is
raised. It must set up the user interface on the screen. To do so, it collaborates with the
JFrame,JTextField,JButton, and JLabelclasses. From our experience with the last Case
Study, we know that we can add the user interface components either to a panel or di-
rectly to the content pane of the frame. If we needed to instantiate multiple calculators
in a window, then using a panel would make sense. Here, however, we need just one
calculator, so we can directly place its components into the content pane. (Case Study
Follow-Up Exercise 12 asks you to rewrite the application using a panel.) We can, there-
fore, use mainto organize the window. Let’s call the application class Calculator.We
know that this application collaborates with the usual user interface library classes,
and it also needs to register the button handlers with the buttons. We can lower the
user interface CRC card, which is now called Calculator.


What happens when the user clicks an operation button? The appropriate button
handler performs a calculation and sends the value to the output register. The only col-
laborations that we need are with the input text field (calling its standard methods to
get its contents and to set them to a new value) and with the ActionEventclass (to get
the name of the event). The four operator buttons are event sources. When the user
clicks one, an actionPerformedmethod is invoked with the event source as an argument.
The processing of the buttons is embedded within this method, the responsibility for
which resides in a class we call NumericHandler.


Class Name: Calculator Superclass: Subclasses:


Responsibilities Collaborations
Initialize user interface JFrame, Container, JLabel,
JButton, JTextField,
Numeric Handler, ClearHandler

User interface window with data register, button, labels
Buttons for four operations
Clear button
Free download pdf