Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^415


Before we go on, let’s simplify the problem somewhat. We will first create a calcula-
tor with only plus and minus functions. After we verify this simplified version of the
application, we can add division and multiplication operations. (See Case Study Follow-
Up Exercise 10.)


The responsibility of main, creating the user interface, is similar to what we’ve done
in several previous applications. Does this mean that we can just cut and paste the
algorithms? No, the objects in the window are not the same, but the steps used to
create them are the same, so we already know how to write the outline of the
algorithm. The steps shown in color require further expansion. We’re applying
functional decomposition to simplify the problem-solving process.


Instantiate Each Interface Object
Set calcFrame to address of new JFrame
Get content pane from calcFrame and assign its address to calcPane
Set up calcPane as a four-row, two-column grid
Set resultLabel to address of new JLabel, "Result:"
Set register to address of new JLabel, "0.0"
Set inputField to address of new JTextField, empty with 10 spaces
Set add to address of new JButton, "+"
Set subtract to address of new JButton, "-"
Set clear to address of new JButton, "Clear"

public static main method (standard arguments)
Instantiate each interface object
Register listeners with buttons
Create the frame
Get the content pane
Size the frame
Set default close operation
Set layout manager for the pane
Add each interface object to the pane
Make the frame visible

Declare Interface Variables
Declare a JFrame, calcFrame
Declare a Container, calcPane
Declare a JLabel, resultLabel
Declare a JLabel, register
Declare a JLabel, entryLabel, for prompting
Declare a JTextField, inputField, for input
Declare a JButton, add
Declare a JButton, subtract
Declare a JButton, clear
Free download pdf