Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
630
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

Rule 4 generates larger, more involved and more deeply nested statements. The diagrams that emerge from applying the rules in Fig. 5.21 constitute the set of all possible structured activity diagrams and hence the set of all possible structured programs. The beauty of the structured approach is that we use only seven simple single-entry/single-exit control statements and assemble them in only two simple ways.

If the rules in Fig. 5.21 are followed, an "unstructured' activity diagram (like the one in Fig. 5.25) cannot be created. If you are uncertain about whether a particular diagram is structured, apply the rules of Fig. 5.21 in reverse to reduce the diagram to the simplest activity diagram. If you can reduce it, the original diagram is structured; otherwise, it is not.

Figure 5.25. "Unstructured" activity diagram.

(This item is displayed on page 213 in the print version)

[View full size image]

Structured programming promotes simplicity. Bohm and Jacopini have given us the result that only three forms of control are needed to implement an algorithm:

[Page 211]

Sequence

Selection

Repetition

The sequence structure is trivial. Simply list the statements to execute in the order in which they should execute. Selection is implemented in one of three ways:

if statement (single selection)

if...else statement (double selection)

switch statement (multiple selection)

In fact, it is straightforward to prove that the simple if statement is sufficient to provide any form of selectioneverything that can be done with the if...else statement and the switch statement can be implemented by combining if statements (although perhaps not as clearly and efficiently).

Repetition is implemented in one of three ways:

while statement

do...while statement

for statement

It is straightforward to prove that the while statement is sufficient to provide any form of repetition. Everything that can be done with the do...while statement and the for statement can be done with the while statement (although perhaps not as conveniently).

[Page 212]

Combining these results illustrates that any form of control ever needed in a Java program can be expressed in terms of

sequence

if statement (selection)

while statement (repetition)

and that these can be combined in only two waysstacking and nesting. indeed, structured programming is the essence of simplicity.

[Page 213]

5.10. (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals

This section introduces two other shapes you can draw using the graphics features in Javarectangles and ovals. To draw rectangles and ovals, we call Graphics methods drawRect and drawOval, respectively, as demonstrated in Fig. 5.26.

Figure 5.26. Drawing a cascade of shapes based on the user's choice.

(This item is displayed on pages 213 - 214 in the print version)

1// Fig. 5.26: Shapes.java

2// Demonstrates drawing different shapes.

3import java.awt.Graphics;

4import javax.swing.JPanel;

5

6public class Shapes extends JPanel

7{

8

private int choice; // user's choice of which shape to draw

9

 

10// constructor sets the user's choice

11public Shapes( int userChoice )

12{

13choice = userChoice;

14} // end Shapes constructor

15

16 // draws a cascade of shapes starting from the top left corner

17public void paintComponent( Graphics g )

18{

19super.paintComponent( g );

20

21 for ( int i = 0; i < 10; i++ )

22{

23// pick the shape based on the user's choice

24switch ( choice )

25{

26

case 1

: //

draw rectangles

 

 

 

27

g.drawRect(

10

+ i * 10,

10

+ i * 10,

28

 

50

+

i *

10,

50 + i

*

10

);

29

break

;

 

 

 

 

 

 

30

case 2

: //

draw ovals

 

 

 

31

g.drawOval(

10

+ i * 10,

10

+ i * 10,

32

 

50

+

i *

10,

50 + i

*

10

);

33

break;

 

 

 

 

 

 

34} // end switch

35} // end for

36} // end method paintComponent

37} // end class Shapes

Line 6 begins the class declaration for Shapes, which extends JPanel.Shapes contains one instance variable, choice, declared on line 8, that determines whether paintComponent should draw rectangles or ovals. The Shapes constructor at lines 1114 initializes choice with the value passed in parameter

userChoice.

Method paintComponent (lines 1736) performs the actual drawing. Remember, the first statement in every paintComponent method should be a call to super.paintComponent, as in line 19. The for statement (lines 2135) loops 10 times to draw 10 shapes. The switch statement (Lines 2434) chooses between drawing rectangles and drawing ovals.

If choice is 1, then the program draws a rectangle. Lines 2728 call Graphics method drawRect. Method drawRect requires four arguments. The first two arguments represent the x- and y-coordinates of the upper-left corner of the rectangle. The next two represent the width and the height of the rectangle. In this example, we start at a position 10 pixels down and 10 pixels right of the top-left corner, and every iteration of the loop moves the upper-left corner another 10 pixels down and to the right. The width and the height of the rectangle start at 50 pixels and increase by 10 pixels in each iteration.

[Page 214]

If choice is 2, then the program performs a similar operation, drawing an oval instead of a rectangle. When drawing an oval, an imaginary rectangle called a bounding rectangle is created, and an oval that touches the midpoints of all four sides of the bounding rectangle is placed inside. Method drawOval (lines 3132) requires the same four arguments as method drawRect. The arguments specify the position and size of the bounding rectangle for the oval. The values passed to drawOval in this example are exactly the same as the values passed to drawRect in lines 2728. Since the width and height of the bounding rectangle are identical in this example, lines 2728 draw a circle. You may modify the program to draw both rectangles and ovals to see how drawOval and drawRect are related.

Figure 5.27 is responsible for handling input from the user and creating a window to display the appropriate drawing based on the user's response. Line 3 imports JFrame to handle the display, and Line 4 imports JOptionPane to handle the input.

Figure 5.27. Obtaining user input and creating a JFrame to display

Shapes.

(This item is displayed on page 215 in the print version)

1 // Fig. 5.27: ShapesTest.java

2 // Test application that displays class Shapes.

3import javax.swing.JFrame;

4import javax.swing.JOptionPane;

6public class ShapesTest

7

{

8

public static void main( String args[] )

9{

10// obtain user's choice

11String input = JOptionPane.showInputDialog(

12"Enter 1 to draw rectangles\n" +

13"Enter 2 to draw ovals" );

14

15 int choice = Integer.parseInt( input ); // convert input to int 16

17// create the panel with the user's input

18Shapes panel = new Shapes( choice );

19

20 JFrame application = new JFrame(); // creates a new JFrame 21

22application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

23application.add( panel ); // add the panel to the frame

24application.setSize( 300, 300 ); // set the desired size

25application.setVisible( true ); // show the frame

26} // end main

27} // end class ShapesTest

[View full size image]

Lines 1113 prompt the user with an input dialog and store the user's response in variable input. Line 15 uses Integer method parseInt to convert the String entered by the user to an int and stores the result in variable choice. An instance of class Shapes is created at line 18, with the user's choice passed to the constructor. Lines 2025 perform the standard operations for creating and setting up a windowcreating a frame, setting it to exit the application when closed, adding the drawing to the frame, setting the frame size and making it visible.

[Page 216]

GUI and Graphics Case Study Exercises

5.1Draw 12 concentric circles in the center of a JPanel (Fig. 5.28). The innermost circle should have a radius of 10 pixels, and each successive circle should have a radius 10 pixels larger than the previous one. Begin by finding the center of the JPanel. To get the upper-left corner of a circle, move up one radius and to the left one radius from the center. The width and height of the bounding rectangle is the diameter of the circle (twice the radius).

Figure 5.28. Drawing concentric circles.

5.2Modify Exercise 5.16 from the end-of-chapter exercises to read input using dialogs and to display the bar chart using rectangles of varying lengths.

[Page 216 (continued)]

5.11. (Optional) Software Engineering Case Study: Identifying Objects' States and Activities

In Section 4.15, we identified many of the class attributes needed to implement the ATM system and added them to the class diagram in Fig. 4.24. In this section, we show how these attributes represent an object's state. We identify some key states that our objects may occupy and discuss how objects change state in response to various events occurring in the system. We also discuss the workflow, or activities, that objects perform in the ATM system. We present the activities of BalanceInquiry and Withdrawal transaction objects in this section.

State Machine Diagrams

Each object in a system goes through a series of states. An object's current state is indicated by the values of the object's attributes at a given time. State machine diagrams (commonly called state diagrams ) model several states of an object and show under what circumstances the object changes state. Unlike the class diagrams presented in earlier case study sections, which focused primarily on the structure of the system, state diagrams model some of the behavior of the system.

Figure 5.29 is a simple state diagram that models some of the states of an object of class ATM. The UML represents each state in a state diagram as a rounded rectangle with the name of the state placed inside it. A solid circle with an attached stick arrowhead designates the initial state. Recall that we modeled this state information as the Boolean attribute userAuthenticated in the class diagram of Fig. 4.24. This attribute is initialized to false, or the "User not authenticated" state, according to the state diagram.

[Page 217]

Figure 5.29. State diagram for the ATM object.

[View full size image]

The arrows with stick arrowheads indicate transitions between states. An object can transition from one state to another in response to various events that occur in the system. The name or description of the event that causes a transition is written near the line that corresponds to the transition. For example, the ATM object changes from the "User not authenticated" state to the "User authenticated" state after the database authenticates the user. Recall from the requirements document that the database authenticates a user by comparing the account number and PIN entered by the user with those of an account in the database. If the database indicates that the user has entered a valid account number and the correct PIN, the ATM object transitions to the "User authenticated" state and changes its userAuthenticated attribute to a value of true. When the user exits the system by choosing the "exit" option from the main menu, the ATM object returns to the "User not authenticated" state.

Software Engineering Observation 5.5

Software designers do not generally create state diagrams showing every possible state and state transition for all attributesthere are simply too many of them. State diagrams typically show only key states and state transitions.

Activity Diagrams

Like a state diagram, an activity diagram models aspects of system behavior. Unlike a state diagram, an activity diagram models an object's workflow (sequence of events) during program execution. An activity diagram models the actions the object will perform and in what order. The activity diagram in Fig. 5.30 models the actions involved in executing a balance-inquiry transaction. We assume that a BalanceInquiry object has already been initialized and assigned a valid account number (that of the current user), so the object knows which balance to retrieve. The diagram includes the actions that occur after the user selects a balance inquiry from the main menu and before the ATM returns the user to the main menua BalanceInquiry object does not perform or initiate these actions, so we do not model them here. The diagram begins with retrieving the balance of the account from the database. Next, the BalanceInquiry displays the balance on the screen. This action completes the execution of the transaction. Recall that we have chosen to represent an account balance as both the availableBalance and totalBalance attributes of class Account, so the actions modeled in Fig. 5.30 refer to the retrieval and display of both balance attributes.

Figure 5.30. Activity diagram for a BalanceInquiry object.

(This item is displayed on page 218 in the print version)

[View full size image]

The UML represents an action in an activity diagram as an action state modeled by a rectangle with its left and right sides replaced by arcs curving outward. Each action state contains an action expressionfor example, "get balance of account from database"that specifies an action to be performed. An arrow with a stick arrowhead connects two action states, indicating the order in which the actions represented by the action states occur. The solid circle (at the top of Fig. 5.30) represents the activity's initial statethe beginning of the workflow before the object performs the modeled actions. In this case, the transaction first executes the "get balance of account from database" action expression. The transaction then displays both balances on the screen. The solid circle enclosed in an open circle (at the bottom of Fig. 5.30) represents the final statethe end of the workflow after the object performs the modeled actions. We used UML activity diagrams to illustrate the flow of control for the control statements presented in Chapters 45.

[Page 218]

Figure 5.31 shows an activity diagram for a withdrawal transaction. We assume that a Withdrawal object has been assigned a valid account number. We do not model the user selecting a withdrawal from the main menu or the ATM returning the user to the main menu because these are not actions performed by a Withdrawal object. The transaction first displays a menu of standard withdrawal amounts (shown in Fig. 2.19) and an option to cancel the transaction. The transaction then receives a menu selection from the user. The activity flow now arrives at a decision (a fork indicated by the small diamond symbol). [ Note: A decision was known as a branch in earlier versions of the UML.] This point determines the next action based on the associated guard condition (in square brackets next to the transition), which states that the

transition occurs if this condition is met. If the user cancels the transaction by choosing the "cancel" option from the menu, the activity flow immediately skips to the final state. Note the merge (indicated by the small diamond symbol) where the cancellation flow of activity joins the main flow of activity before reaching the activity's final state. If the user selects a withdrawal amount from the menu, Withdrawal sets amount (an attribute originally modeled in Fig. 4.24) to the value chosen by the user.

Figure 5.31. Activity diagram for a withdrawal transaction.

(This item is displayed on page 219 in the print version)

[View full size image]