© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application 16.2 Introducing Arrays 16.3 Declaring and Creating Arrays 16.4 Constructing the Flag Quiz Application 16.5 Sorting Arrays 16.6 Wrap-Up Tutorial 16 – Flag Quiz Application Introducing One-Dimensional Arrays and JComboBox es
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Objective In this tutorial, you will learn to: –Create and initialize arrays. –Store information in an array. –Refer to individual elements of an array. –Sort arrays. –Use JComboBox es to display options in a drop-down list.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application Data Structures –Group together and organize related data Arrays –Consist of data items of the same type –Index GUI Component JComboBox –Presents user options in a drop-down list
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.1 Running the completed Flag Quiz application. JComboBox contains answers (country names) JLabel displays a flag
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.2 Selecting an answer from the JComboBox. Scrollbar in JComboBox ’s drop-down list Answer being selected
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.3 Submitting the correct answer. User can select the next flag Feedback provided to the user
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.4 Displaying the next flag. outputJTextField is cleared Submit JButton is re-enabled
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.5 Submitting an incorrect answer.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Flag Quiz Application (Cont.) Figure 16.6 Finishing the quiz. JComboBox is disabled when the quiz ends
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introducing Arrays Position number –A value that indicates a specific location within an array –Begin at 0 and range as high as one less than the array length Element –A piece of an array that can hold a single value Zeroth element –The first element of an array (e.g. unitsSold[0] ) Index or subscript –The position number in brackets
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introducing Arrays (Cont.) Indexed array name –The array name followed by an index enclosed in brackets –Can be used on the left side of an assignment statement to place a new value into an array element. Name Value One-dimensional –Array that uses only one index
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introducing Arrays (Cont.) Figure 16.7 Array unitsSold consisting of 13 elements.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays Array bounds –Determines what indices can be used to access an array element Array initializer –Specifies the initial values of the elements in the array –Java determines the array’s size and bounds from the number elements in the initializer int unitsSold[]; unitsSold = new int[ 13 ]; int salesPerDay[] = { 0, 2, 3, 6, 1, 4, 5, 6 };
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays (Cont.) Figure 16.8 Running the Sum Array template application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays (Cont.) Figure 16.9 Declaring an array in the sumArrayJButtonActionPerformed method. Creating an array of int s
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays (Cont.) Figure Summing the values of an array’s elements. Retrieve the value of each element and add it to the total, one at a time arrayName.length –Contains the number of elements in arrayName
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays (Cont.) Figure Displaying the sum of the values of an array’s elements.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Declaring and Creating Arrays (Cont.) Figure Running the completed Sum Array application. Total value of array elements
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application When the user begins the application Sort the array of country names alphabetically Place country names in the JComboBox Randomly select the first flag and store the correct answer Display the first flag When the user clicks the Submit JButton Retrieve the index of the selected country name from the JComboBox If the selected country’s index matches the index of the current flag Display "Correct!" in the feedback JTextField Else Display "Sorry, incorrect." in the feedback JTextField If five images have been displayed Append "Done!" to the feedbackJTextField’s text Disable the JButtons and JComboBox Else Disable the Submit JButton Enable the Next Flag JButton
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) When the user clicks the Next Flag JButton Randomly select a flag that has not been chosen previously Display the new flag Clear the feedback JTextField Set the JComboBox to display its first item Enable the Submit JButton Disable the Next Flag JButton
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Creating and initializing the String array that stores the country names. Creating an array of String s to store country names
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Array of type boolean that keeps track of displayed flags. Creating an array of boolean values
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Declaring instance variables. Declaring instance variables
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Setting selectCountryJComboBox ’s items. Adding data to a JComboBox
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Setting selectCountryJComboBox ’s bounds. Set the bounds of the selectCountryJComboBox
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Setting the maximum number of items displayed in the selectCountryJComboBox. Set the number of items displayed in the selectCountryJComboBox Property maximumRowCount –Determines how many items in the JComboBox are displayed at once –If the total number of items in the JComboBox exceeds this number, a vertical scrollbar will be automatically added to the drop-down list
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Flag Quiz application with selectCountryJComboBox. selectCountryJComboBox displays country names
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Generating a unique index. Determining if a country ’ s flag has been previously displayed
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Updating the flagsUsed array for the new flag. Indicate that a flag is now used
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Returning the unique index. Returning the value of randomNumber
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Choosing a random country name. Getting index of unused flag Retrieving the flag’s corresponding country name Method getItemAt –Takes an int representing an index –Returns the value at that index
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Creating the path to the image. Creating the path name of the flag’s image
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Displaying a flag image. Use method setIcon to display the flag image
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Displaying a flag when your application is run. Displaying a flag when the application is first run
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Flag Quiz application displaying initial flag. Initial flag is displayed
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Checking the user’s answer. Retrieve user’s answerDisplaying proper feedback Property selectedIndex –Stores the index of the JComobBox ’s currently selected item Method getSelectedIndex
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Testing whether the quiz is finished. Actions to perform if quiz is over
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Enable user to display next flag if quiz is not over. Allow user to continue
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Flag Quiz application that allows user to submit an answer.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Displaying the next flag. Displaying the next flag for the user to identify
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Allowing the user to enter the next answer. Actions to perform for next question Method setSelectedIndex
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Flag Quiz Application (Cont.) Figure Flag Quiz application with working Submit and Next Flag JButton s. Items are not yet alphabetized Entering a correct answer Application when quiz is finished
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Sorting Arrays Sorting –Arranging data in some particular order Pass-by-value –A copy of the argument’s value is passed to the method –Changes made to the copy of the argument do not affect the original variable’s value –Primitive types are always passed by value Pass-by-reference –The called method is given access directly to the argument in the caller –The original data in the caller can be modified by the called method –Objects are always passed by reference
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Sorting Arrays (Cont.) Figure Sorting the array of country names. Alphabetizing the country names in the array Method Arrays.sort –Sorts the values in the array into ascending alphabetical order
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Sorting Arrays (Cont.) Figure Flag Quiz application running. Items now listed in alphabetical order
2004 Prentice Hall, Inc. All rights reserved. Outline 50 FlagQuiz.java (1 of 11) 1 // Tutorial 16: FlagQuiz.java 2 // Quiz the user on their knowledge of flags. The user must try to 3 // match five flags to their countries. 4 import java.util.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 import javax.swing.border.*; 9 10 public class FlagQuiz extends JFrame 11 { 12 // array of country names 13 private String[] countries = { "Russia", "China", "United States", 14 "Italy", "Australia", "South Africa", "Brazil", "Spain" }; // boolean array tracks displayed flags 17 private boolean[] flagsUsed = new boolean[ countries.length ]; private int currentIndex; // contains the index of current flag // tracks the number of flags that have been displayed 22 private int count = 1; 23 Creating an array of String s to store country names Creating a boolean array Variable currentIndex stores the index of the flag being displayed Variable count stores the number of flags being displayed
2004 Prentice Hall, Inc. All rights reserved. Outline 51 FlagQuiz.java (2 of 11) 24 // JPanel and JLabel for displaying a flag image 25 private JPanel flagJPanel; 26 private JLabel flagIconJLabel; // JLabel and JComboBox for choosing a country 29 private JLabel selectCountryJLabel; 30 private JComboBox selectCountryJComboBox; // JTextField for giving the user feedback 33 private JTextField feedbackJTextField; // JButton to submit an answer 36 private JButton submitJButton; // JButton to display the next flag 39 private JButton nextFlagJButton; // no-argument constructor 42 public FlagQuiz() 43 { 44 createUserInterface(); 45 } 46
2004 Prentice Hall, Inc. All rights reserved. Outline 52 FlagQuiz.java (3 of 11) 47 // create and position GUI components; register event handlers 48 private void createUserInterface() 49 { 50 // get content pane for attaching GUI components 51 Container contentPane = getContentPane(); // enable explicit positioning of GUI components 54 contentPane.setLayout( null ); // set up flagJPanel 57 flagJPanel = new JPanel(); 58 flagJPanel.setBounds( 16, 8, 100, 90 ); 59 flagJPanel.setLayout( null ); 60 flagJPanel.setBorder( new TitledBorder( "Flag" ) ); 61 contentPane.add( flagJPanel ); // set up flagIconJLabel 64 flagIconJLabel = new JLabel(); 65 flagIconJLabel.setBounds( 10, 14, 80, 80 ); 66 flagIconJLabel.setHorizontalAlignment( JLabel.CENTER ); 67 flagJPanel.add( flagIconJLabel ); 68
2004 Prentice Hall, Inc. All rights reserved. Outline 53 FlagQuiz.java (4 of 11) 69 // set up selectCountryJLabel 70 selectCountryJLabel = new JLabel(); 71 selectCountryJLabel.setBounds( 136, 8, 88, 21 ); 72 selectCountryJLabel.setText( "Select country:" ); 73 contentPane.add( selectCountryJLabel ); Arrays.sort( countries ); // sort the array // set up selectCountryJComboBox 78 selectCountryJComboBox = new JComboBox( countries ); 79 selectCountryJComboBox.setBounds( 136, 32, 135, 21 ); 80 selectCountryJComboBox.setMaximumRowCount( 3 ); 81 contentPane.add( selectCountryJComboBox ); displayFlag(); // display first flag // set up feedbackJTextField 86 feedbackJTextField = new JTextField(); 87 feedbackJTextField.setBounds( 136, 64, 135, 32 ); 88 feedbackJTextField.setHorizontalAlignment( 89 JTextField.CENTER ); 90 feedbackJTextField.setEditable( false ); 91 contentPane.add( feedbackJTextField ); 92 Alphabetizing country names in the array Customizing the selectCountry JComboBox Displaying the initial flag
2004 Prentice Hall, Inc. All rights reserved. Outline 54 FlagQuiz.java (5 of 11) 93 // set up submitJButton 94 submitJButton = new JButton(); 95 submitJButton.setBounds( 287, 8, 88, 32 ); 96 submitJButton.setText( "Submit" ); 97 contentPane.add( submitJButton ); 98 submitJButton.addActionListener( new ActionListener() // anonymous inner class 101 { 102 // event handler called when submitJButton is pressed 103 public void actionPerformed( ActionEvent event ) 104 { 105 submitJButtonActionPerformed( event ); 106 } } // end anonymous inner class ); // end call to addActionListener 111
2004 Prentice Hall, Inc. All rights reserved. Outline 55 FlagQuiz.java (6 of 11) 112 // set up nextFlagJButton 113 nextFlagJButton = new JButton(); 114 nextFlagJButton.setBounds( 287, 48, 88, 32 ); 115 nextFlagJButton.setText( "Next Flag" ); 116 nextFlagJButton.setEnabled( false ); 117 contentPane.add( nextFlagJButton ); 118 nextFlagJButton.addActionListener( new ActionListener() // anonymous inner class 121 { 122 // event handler called when nextFlagJButton is pressed 123 public void actionPerformed( ActionEvent event ) 124 { 125 nextFlagJButtonActionPerformed( event ); 126 } } // end anonymous inner class ); // end call to addActionListener // set properties of application’s window 133 setTitle( "Flag Quiz" ); // set title bar string 134 setSize( 390, 135 ); // set window size 135 setVisible( true ); // display window 136
2004 Prentice Hall, Inc. All rights reserved. Outline 56 FlagQuiz.java (7 of 11) 137 } // end method createUserInterface // return an unused random number 140 private int getUniqueRandomNumber() 141 { 142 Random generator = new Random(); 143 int randomNumber; // generate random numbers until unused flag is found 146 do 147 { 148 randomNumber = generator.nextInt( 8 ); 149 } 150 while ( flagsUsed[ randomNumber ] == true ); // indicate that flag has been used 153 flagsUsed[ randomNumber ] = true; return randomNumber; } // end method getUniqueRandomNumber 158 Object used to create random values Determining if a country’s flag has been displayed previously Indicating that an unused flag will be displayed and returning the flag’s index for use
2004 Prentice Hall, Inc. All rights reserved. Outline 57 FlagQuiz.java (8 of 11) 159 // choose a flag and display it in the JLabel 160 private void displayFlag() 161 { 162 currentIndex = getUniqueRandomNumber(); // get an unused flag // create the path for that flag 165 String country = 166 ( String ) selectCountryJComboBox.getItemAt( currentIndex ); 167 String countryPath = "images/" + country + ".png"; // set the flagIconJLabel to display the flag 170 flagIconJLabel.setIcon( new ImageIcon( countryPath ) ); } // end method displayFlag 173 Getting index of unused flag Retrieving the flag’s corresponding country name Path name of flag images Displaying an unused flag
2004 Prentice Hall, Inc. All rights reserved. Outline 58 FlagQuiz.java (9 of 11) 174 // check the answer and update the quiz 175 private void submitJButtonActionPerformed( ActionEvent event ) 176 { 177 // determine whether the answer was correct 178 if ( selectCountryJComboBox.getSelectedIndex() 179 == currentIndex ) 180 { 181 feedbackJTextField.setText( "Correct!" ); 182 } 183 else // if an incorrect answer is given 184 { 185 feedbackJTextField.setText( "Sorry, incorrect." ); 186 } 187 Retrieving the user’s answer and displaying feedback
2004 Prentice Hall, Inc. All rights reserved. Outline 59 FlagQuiz.java (10 of 11) 188 // inform user if quiz is over 189 if ( count == 5 ) 190 { 191 feedbackJTextField.setText( 192 feedbackJTextField.getText() + " Done!" ); 193 nextFlagJButton.setEnabled( false ); 194 submitJButton.setEnabled( false ); 195 selectCountryJComboBox.setEnabled( false ); 196 } 197 else // if less than 5 flags have been displayed 198 { 199 submitJButton.setEnabled( false ); 200 nextFlagJButton.setEnabled( true ); 201 } } // end method submitJButtonActionPerformed // display next flag in the quiz 206 private void nextFlagJButtonActionPerformed( ActionEvent event ) 207 { 208 displayFlag(); // display next flag 209 count++; 210 Determining if the quiz is over Displaying the next flag for the user to identify
2004 Prentice Hall, Inc. All rights reserved. Outline 60 FlagQuiz.java (11 of 11) 211 // reset GUI components to initial states 212 feedbackJTextField.setText( "" ); 213 selectCountryJComboBox.setSelectedIndex( 0 ); 214 submitJButton.setEnabled( true ); 215 nextFlagJButton.setEnabled( false ); } // end method nextFlagJButtonActionPerformed // main method 220 public static void main( String args[] ) 221 { 222 FlagQuiz application = new FlagQuiz(); 223 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end method main } // end class FlagQuiz Setting the JComboBox to display its first item